Skip to content

Instantly share code, notes, and snippets.

@carlosocarvalho
Last active September 8, 2016 20:40
Show Gist options
  • Save carlosocarvalho/095c4da529f7b950345e75b84dbdca4d to your computer and use it in GitHub Desktop.
Save carlosocarvalho/095c4da529f7b950345e75b84dbdca4d to your computer and use it in GitHub Desktop.
Eventos com Codeigniter 3
#vamos configurar nosso autoload da library Events;
#config/autload.php
<?php
/*
| -------------------------------------------------------------------
| Auto-load Libraries
| -------------------------------------------------------------------
| These are the classes located in the system/libraries folder
| or in your application/libraries folder.
|
| Prototype:
|
| $autoload['libraries'] = array('database', 'session', 'xmlrpc');
*/
$autoload['libraries'] = array('database', 'session', 'table','events');
Adiocione esses linhas para seu arquivo.
Essa pasta será onde vamos adicionar nossos arquivos de eventos.
Isso é um pouco fora da curva do php mas tudo bem.
"autoload":{
"psr-4":{
"Events\\":"application\\Events\\",
}
}
1 -Primeiro vamos dar uma olhada de como será nossa estrutura de pastas para isso.
2 -Vamos criar uma nova pasta dentro da nossa pasta aplicaction
--application
-Events
-core
-config
-controllers
-models
-libraries
-hooks
...
- Vamos criar o aquivo dentro de Libraries
<?php
class Events {
/**
* @var array An array of listeners
*/
protected static $_listeners = array();
// ------------------------------------------------------------------------
/**
* Register
*
* Registers a Callback for a given event
*
* @access public
* @param string The name of the event
* @param array The callback for the Event
* @return void
*/
public static function register($event, array $callback)
{
$key = get_class($callback[0]).'::'.$callback[1];
self::$_listeners[$event][$key] = $callback;
self::log_message('debug', 'Events::register() - Registered "'.$key.' with event "'.$event.'"');
}
// ------------------------------------------------------------------------
/**
* Trigger
*
* Triggers an event and returns the results. The results can be returned
* in the following formats:
*
* 'array'
* 'json'
* 'serialized'
* 'string'
*
* @access public
* @param string The name of the event
* @param mixed Any data that is to be passed to the listener
* @param string The return type
* @return mixed The return of the listeners, in the return type
*/
public static function trigger($event, $data = '', $return_type = 'string')
{
self::log_message('debug', 'Events::trigger() - Triggering event "'.$event.'"');
$calls = array();
if (self::has_listeners($event))
{
foreach (self::$_listeners[$event] as $listener)
{
if (is_callable($listener))
{
$calls[] = call_user_func($listener, $data);
}
}
}
return self::_format_return($calls, $return_type);
}
// ------------------------------------------------------------------------
/**
* Format Return
*
* Formats the return in the given type
*
* @access protected
* @param array The array of returns
* @param string The return type
* @return mixed The formatted return
*/
protected static function _format_return(array $calls, $return_type)
{
self::log_message('debug', 'Events::_format_return() - Formating calls in type "'.$return_type.'"');
switch ($return_type)
{
case 'json':
return json_encode($calls);
break;
case 'serialized':
return serialize($calls);
break;
case 'string':
$str = '';
foreach ($calls as $call)
{
$str .= $call;
}
return $str;
break;
default:
return $calls;
break;
}
return FALSE;
}
// ------------------------------------------------------------------------
/**
* Has Listeners
*
* Checks if the event has listeners
*
* @access public
* @param string The name of the event
* @return bool Whether the event has listeners
*/
public static function has_listeners($event)
{
self::log_message('debug', 'Events::has_listeners() - Checking if event "'.$event.'" has listeners.');
if (isset(self::$_listeners[$event]) AND count(self::$_listeners[$event]) > 0)
{
return TRUE;
}
return FALSE;
}
// ------------------------------------------------------------------------
/**
* Log Message
*
* Pulled out for unit testing
*
* @param string $type
* @param string $message
* @return void
*/
public static function log_message($type = 'debug', $message = '')
{
if (function_exists('log_message'))
{
log_message($type, $message);
}
}
}
//** libraries/Events
E por ultimo nosso arquivo hooks.php
E não vamos esquecer de habilitar hooks em config.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| Hooks
| -------------------------------------------------------------------------
| This file lets you define "hooks" to extend CI without hacking the core
| files. Please see the user guide for info:
|
| http://codeigniter.com/user_guide/general/hooks.html
|
|
*/
$hook['post_controller_constructor'][]= array(
'class' => 'RegisterEventAutoload',
'function' => 'handler',
'filename' => 'RegisterEventAutoload.php',
'filepath' => 'hooks',
);
<?php
class Register extends CI_Controller{
public function create(){
$this->load->view('user/create');
}
public function store(){
$data = $this->input->post();
if($this->db->insert('user', $data))
Events::trigger('user:create' , $data);
}
}
Agora vamos criar um arquivo onde vamos centralizar todos os registros dos nossos eventos.
<?php
$config = [
'user:create' => [
Events\RegisterUserSMSEvent::class,
Events\RegisterUserMailerEvent::class
],
'user:update' => [
Events\RegisterUserMailerEvent::class
],
'user:delete' => [
Events\RegisterUserSMSEvent::class,
Events\RegisterUserMailerEvent::class
]
];
return $config;
//** config/register_events.php
Vamos adicionar esse nosso arquivo na pasta hooks
<?php
//application/hooks
class RegisterEventAutoload{
/**
* [handler on start classe events
* @return [type] [description]
*/
public function handler(){
$ci = get_instance();
$ci->load->config('register_events', true);
$registered = config_item('register_events');
if(! $registered) return;
$this->registerAllEvents($registered);
}
/**
* [registerAllEvents description]
* @param [type] $events [description]
* @return [type] [description]
*/
private function registerAllEvents($events){
foreach ($events as $key => $ev) {
foreach ($ev as $classEvent) {
if(!is_object($classEvent))
$classEvent = new $classEvent();
Events::register($key , [$classEvent , 'handler']);
}
}
}
}
//** hooks/RegisterEventAutoload.php
<?php
namespace Events;
class RegisterUserMailerEvent {
public function handler($data){
//script para enviar e-mail.
if( mailer()->send($data))
return true;
user
return false;
}
}
//** Events\RegisterUserMailerEvent.php
<?php
namespace Events;
class RegisterUserSMSEvent {
public function handler($data){
//script para enviar sms
if(sms()->send($data))
return true;
return false;
}
}
//** Events\RegisterUserSMSEvent.php
1 - Vamos fazer uso da psr-4, então vamos precisar configurar nosso composer
2 - Vamos configurar um projeto em composer caso você não tenha instalado o projeto usando o composer.
3 - Vamos configurar nosso composer autoload em application/config/config.php ['composer_autolaod'] configurar para suas configurações;
4 - agora precisamos configurar nosso composer.json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment