On Github etienneroudeix / talks-eventProgramming
Talking : Etienne Roudeix / @__etienne
mouse actions - key presses
different logic
aim : modularity
public function createUser($login, $password, $email) { if (User::exists($login) || !filter_var($email, FILTER_VALIDATE_EMAIL)) { throw new RuntimeException('Bad login or email'); //check data } $user = User::create([ //insert in database 'login' => $login, 'password' => $password, 'email' => $email, ]); Mail::send($email, "Welcome", "Glad you joined us"); //send email return $user; }
public function createUser($login, $password, $email) { if (strlen($password) < 6) { throw new RuntimeException('Password is not complex enough'); } return parent::createUser($login, $password, $email); }
public function createUser($login, $password, $email) { if (strlen($password) < 6) { throw new RuntimeException('Password is not complex enough'); } $user = parent::createUser($login, $password, $email); $user->created_at = new DateTime(); $user->save(); return $user; }
rewrite the whole function
update issues
public function createUser($login, $password, $email) { $user = User::factory([ 'login' => $login, 'password' => $password, 'email' => $email, ]); Event::fire('user.create.check', $user); $user->save(); //insert in database Event::fire('user.create.send_mail', $user); Event::fire('user.created', $user); return $user; }
Event::listen( 'user.create.check', function(User &$user) { if (User::exists($user->login) || !filter_var($user->email, FILTER_VALIDATE_EMAIL)) { throw new RuntimeException('Bad login or email'); } }, 0 //priority );
Event::listen( 'user.create.send_mail', function(User &$user) { Mail::send($user->email, "Welcome", "Glad you joined us"); }, 0 //priority );
Event::listen( 'user.create.check', function(User &$user) { if (strlen($user->password) < 6) { throw new RuntimeException('Password is not complex enough'); } }, 10 //greater priority );
Event::listen( 'user.create.check', function(User &$user) { $user->created_at = new DateTime(); }, -10 //lower priority );
Event::listen( 'user.create.send_mail', function(User &$user) { if (!$user->worthIt()) { return false; // stop propagation } }, 10 //greater priority );
all emails in the same MailSubscriber
all admin management in AdminSubscriber
easy pre/post crud modularity
testing => no MailSubscriber, no LogSubscriber
prod => no DebugSubscriber
by Etienne Roudeix / @__etienne