2

I have some code, that I need to apply for multiple Tables' Entities

similar to the example here http://book.cakephp.org/3.0/en/orm/entities.html#accessors-mutators

 protected function _setTitle($title)
 {
     // code to make re-usable 

     return $title;
 }

Where can I move my code, so I can access it from multiple Entities. I tried a function inside Behavior, but it did not work.

Thanks

dav
  • 8,931
  • 15
  • 76
  • 140
  • @AD7six, I need to set a new field, but based on some conditions, which I read from `Configure::read`. thanks – dav Jul 05 '16 at 09:43

1 Answers1

2

You can do this one of two ways. First, using a trait (a bit like what you were trying to achieve with a behavior):-

class Example extends Entity
{
    use TitleTrait;
}

trait TitleTrait 
{

    protected function _setTitle($title)
    {
        return $title;
    }

}

Second way is by using inheritance:-

class Example extends CustomEntity
{

}

abstract class CustomEntity extends Entity
{

    protected function _setTitle($title)
    {
        return $title;
    }

}
drmonkeyninja
  • 8,490
  • 4
  • 31
  • 59