Advertisement
Guest User

Example

a guest
Oct 26th, 2015
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.97 KB | None | 0 0
  1. <?php
  2. use yii\base\Model;
  3.  
  4. /*
  5.     Мой класс наследуется от ComponentWithTwoDiffrentMethodsForBehaviors,
  6.     В котором есть поддержка двух методов с поведениями.
  7.     Как мне нужно
  8. */
  9. class NewModel extends ComponentWithTwoDiffrentMethodsForBehaviors
  10. {
  11.     /*
  12.         Здесь хранятся один набор поведений
  13.     */
  14.     public function behaviors()
  15.     {
  16.         return [
  17.             [
  18.                 'class' => TimestampBehavior::className(),
  19.                 'createdAtAttribute' => 'created_at',
  20.                 'updatedAtAttribute' => 'updated_at',
  21.             ],
  22.         ];
  23.     }
  24.  
  25.     /*
  26.         Здесь хранятся один набор поведений
  27.     */
  28.     public function behaviors2()
  29.     {
  30.         return [
  31.             [
  32.                 'class' => BlameableBehavior::className(),
  33.                 'createdByAttribute' => 'author_id',
  34.                 'updatedByAttribute' => 'updater_id',
  35.             ],
  36.         ];
  37.     }
  38. }
  39.  
  40.  
  41. /*
  42.     Моя примерная реализация данной задачи
  43. */
  44.  
  45. class ComponentWithTwoDiffrentMethodsForBehaviors extends Model
  46. {
  47.     public $ensureBehaviorsLock = false;
  48.  
  49.     public function behaviors()
  50.     {
  51.         return [];
  52.     }
  53.  
  54.     public function behaviors2()
  55.     {
  56.         return [];
  57.     }
  58.  
  59.     private function attachBehavior2Internal($name, $behaviors2)
  60.     {
  61.         return $this->attachBehavior($name, $behaviors2);
  62.     }
  63.  
  64.     public function ensureBehaviors2()
  65.     {
  66.         foreach ($this->behaviors2() as $name => $behaviors2) {
  67.             $this->attachBehavior2Internal($name, $behaviors2);
  68.         }
  69.     }
  70.  
  71.     public function ensureBehaviors()
  72.     {
  73.         if ($this->ensureBehaviorsLock) {
  74.             return;
  75.         }
  76.  
  77.         $this->ensureBehaviorsLock = true;
  78.  
  79.         parent::ensureBehaviors();
  80.  
  81.         $this->ensureRelations();
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement