Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

May I use properties from a parent class in a trait?

Tags:

php

traits

Is it OK to use properties/methods from parent classes in trait methods?

This code works, but is it good practice?

class Child extends Base{

  use ExampleTrait;

  public function __construct(){
     parent::__construct();
  }

  public function someMethod(){
    traitMethod();
  }

}

trait ExampleTrait{
  protected function traitMethod(){
    // Uses  $this->model from Base class
    $this->model->doSomething();
  }
}
like image 205
ymakux Avatar asked Jan 18 '17 06:01

ymakux


1 Answers

I don't think it's good practice.

Instead you could have a method to fetch your model object, and have that method as an abstract signature in you trait:

trait ExampleTrait {
    abstract protected function _getModel();

    protected function traitMethod() {
        $this->_getModel()->doSomething();
    }
}

class Base {
    protected $_model;

    protected function _getModel() {
        return $this->_model;
    }
}

class Child extends Base {
    use ExampleTrait;

    public function someMethod() {
        $this->traitMethod();
    }
}

Or pass your model as a parameter to your trait method:

trait ExampleTrait {
    protected function traitMethod($model) {
        $model->doSomething();
    }
}

class Base {
    protected $_model;
}

class Child extends Base {
    use ExampleTrait;

    public function someMethod() {
        $this->traitMethod($this->_model);
    }
}

Both of these approaches let you utilize your IDE's type hinting.

like image 165
Joe Avatar answered Oct 27 '22 05:10

Joe