Behaviours
Introduction
Behaviours in Sukarix are traits that can be plugged into classes to extend their functionality. By convention,
an init<TraitName> method should be implemented and is called immediately after the injector creates an instance of
the class using the trait.
Available Behaviours
| Trait | Property | Visibility | Description |
|---|---|---|---|
LogWriter | $logger | protected | A Monolog logger writing to the application log |
HasF3 | $f3 | protected | The Fat-Free Framework instance |
HasSession | $session | protected | The session service |
HasCache | $cache | protected | The cache service, with remember() and forget() helpers |
HasI18n | $i18n | protected | The translation service |
HasMessages | $messages | protected | Flash messages |
HasAssets | $assets | protected | Asset management |
HasQueue | $queueService | protected | The queue service; requires a registered queue service |
HasAccess | $access | private | The ACL service |
HasEvents | $events | private | The event dispatcher |
The init<TraitName> method of each trait is invoked by the Processor, so a class only needs to
use the trait to receive its property:
class MyClass {
use LogWriter;
use HasF3;
}
Warning
HasAccess and HasEvents are private
These two traits declare their property
private. A private trait property is usable inside the class that declares theuse, but is not visible to its subclasses. If you need the property in a class hierarchy, apply the trait in each class that reads it rather than only in the base class.
Singleton Classes
Any singleton class inheriting from Tailored must call Processor::instance()->initialize($this); in its constructor
to ensure that the init<TraitName> methods are called. The Helper base class already does this, so classes extending
Helper (directly or indirectly) only need to call parent::__construct().
Non-Singleton Classes
If a class does not inherit from Tailored, it must call Processor::instance()->initialize($this); in the constructor
to ensure that the init<TraitName> methods are called.
Example Usage
Here’s how you might use these behaviours in a class:
class MyService {
use LogWriter;
use HasF3;
public function __construct() {
Processor::instance()->initialize($this); // Initialise traits manually
}
public function logSomething() {
$this->logger->info('Logging something!', ['context' => 'value']);
}
public function getFrameworkInstance() {
return $this->f3;
}
}
In this example, MyService uses both the LogWriter and HasF3 traits. Since it does not extend Tailored, it
explicitly calls Processor::instance()->initialize($this); in the constructor to ensure that the traits are
initialised.