Advertisement
Guest User

Nette object trait concept

a guest
Apr 4th, 2016
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.65 KB | None | 0 0
  1. <?php
  2. namespace Ntraits;
  3.  
  4. error_reporting(E_ALL);
  5. ini_set('display_errors', 'on');
  6.  
  7. class NotConsumedException extends \Exception
  8. {
  9. }
  10.  
  11.  
  12. trait MultiCallable
  13. {
  14.     public function __call($name, $arguments)
  15.     {
  16.         $r = new \ReflectionClass($this);
  17.         foreach (class_uses(get_called_class()) as $trait) {
  18.             $slash = strrpos($trait, '\\');
  19.             $traitSimpleName = $slash === FALSE ? $trait : substr($trait, $slash + 1);
  20.             $methodName = '_callNette' . $traitSimpleName;
  21.  
  22.             if ($r->hasMethod($methodName)) {
  23.                 $m = $r->getMethod($methodName);
  24.                 $m->setAccessible(TRUE);
  25.                 try {
  26.                     return $m->invoke($this, $name, $arguments);
  27.                 } catch (NotConsumedException $ex) {
  28.                 }
  29.             }
  30.         }
  31.         if ($r->getParentClass() !== FALSE && $r->getParentClass()->hasMethod('__call')) {
  32.             parent::__call($name, $arguments);
  33.         }
  34.     }
  35. }
  36.  
  37. trait Foo
  38. {
  39.     protected function _callNetteFoo()
  40.     {
  41.         echo "callNetteFoo\n";
  42.         throw new NotConsumedException;
  43.     }
  44. }
  45.  
  46. trait Bar
  47. {
  48.     protected function _callNetteBar()
  49.     {
  50.         echo "callNetteBar\n";
  51.         throw new NotConsumedException;
  52.     }
  53. }
  54.  
  55. trait Baz
  56. {
  57.     protected function _callNetteBaz()
  58.     {
  59.         return "callNetteBaz";
  60.     }
  61. }
  62.  
  63.  
  64. class Z
  65. {
  66.     protected function __call($name, $arguments)
  67.     {
  68.         echo "parent class";
  69.     }
  70. }
  71.  
  72. class A extends Z
  73. {
  74.     use MultiCallable, Foo, Bar;
  75.  
  76. }
  77.  
  78. (new A)->foo();
  79.  
  80. class B
  81. {
  82.     use MultiCallable, Foo, Bar, Baz;
  83. }
  84.  
  85. echo (new B)->foo();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement