Skip to content

Instantly share code, notes, and snippets.

@VictorFursa
Created February 8, 2017 09:25
Show Gist options
  • Save VictorFursa/b2f94a342a5fa7d50b3e7efc384cfa40 to your computer and use it in GitHub Desktop.
Save VictorFursa/b2f94a342a5fa7d50b3e7efc384cfa40 to your computer and use it in GitHub Desktop.
EVENT
<?php
Yii::setAlias('@common', dirname(__DIR__));
Yii::setAlias('@frontend', dirname(dirname(__DIR__)) . '/frontend');
Yii::setAlias('@backend', dirname(dirname(__DIR__)) . '/backend');
Yii::setAlias('@console', dirname(dirname(__DIR__)) . '/console');
//dependency injection container
Yii::$container->set(\common\service\SerializerInterface::class, \common\service\JsonSerializer::class);
Yii::$container->set('requestCrawler', [
'class' => \common\service\RequestCrawlerService::class,
'pathToSave' => dirname(__DIR__) . '/file',
'on infoAfterSave' => function($event)
{
$test = new \common\service\Test();
$test->info($event);
}
]);
<?php
namespace common\service;
use Yii;
use yii\base\Component;
class RequestCrawlerService extends Component
{
const EVENT_INFO_AFTER_SAVE = 'infoAfterSave';
/** @var object $serializer */
public $serializer;
/** @var string $pathToSave */
public $pathToSave;
/**
* RequestCrawlerService constructor.
* @param SerializerInterface $serializer
* @param array $config
*/
public function __construct(SerializerInterface $serializer, array $config = [])
{
$this->serializer = $serializer;
parent::__construct($config);
}
/**
* @param $encoded
* @return bool
*/
public function encodedAndSaveFile($encoded)
{
try {
file_put_contents($this->pathToSave . '/' . time() . '.txt', $encoded, FILE_APPEND | LOCK_EX);
$this->trigger(self::EVENT_INFO_AFTER_SAVE);
} catch (\Exception $e) {
Yii::error('ERROR Not save! The problem with the encodedAndSaveFile ' . $e->getMessage(), 'info');
}
return true;
}
}
<?php
namespace common\service;
use Yii;
use yii\base\Event;
class Test
{
/**
* @param Event $event
*/
public function info (Event $event)
{
Yii::info('Successfully saved file! use serializer: ' . get_class($event->sender->serializer), 'info');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment