Skip to content

Instantly share code, notes, and snippets.

@Nex-Otaku
Last active April 25, 2021 20:10
Show Gist options
  • Save Nex-Otaku/0f56603c4d62d5cffb4ec3ab74c47fde to your computer and use it in GitHub Desktop.
Save Nex-Otaku/0f56603c4d62d5cffb4ec3ab74c47fde to your computer and use it in GitHub Desktop.
Custom component for use in Yii 2 application - independent from the framework
<?php
/**
We want to use our custom component e.g. Tracker with Dependecy Injection and all the nice features,
but make it totally independent of framework.
Make it SOLID )
It would be shame to extend our custom component from framework classes, because it would be a hard dependency from framework.
But otherwise we cannot get all those dependencies automatically injected in runtime. What should we do?
Here is one simple way to do it (there are many ways):
1. Creating our pure custom component class Tracker and pass all dependencies in constructor.
2. Creating simple loader TrackerLoader with only one dependency -- Tracker.
3. Bootstrap loader in config file for our app:
/common/config/main.php
'components' => [
'log' => ...
'tracker' => [
'class' => 'common\components\tracker\TrackerLoader',
],
...
4. Now we can call it like this:
<?= \Yii::$app->tracker->getTracker()->register() ?>
*/
class TrackerLoader extends Component
{
/** @var Tracker */
private $tracker;
public function __construct(
Tracker $tracker,
$config = []
)
{
$this->tracker = $tracker;
parent::__construct($config);
}
public function getTracker(): Tracker
{
return $this->tracker;
}
}
class Tracker
{
/** @var UserService */
private $userService;
public function __construct(
UserService $userService
)
{
$this->userService = $userService;
}
public function register(): string
{
$user = $this->userService->getCurrentUser();
$code = ...
return $code;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment