Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp 3 - reusable code for Table Entities

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

like image 231
dav Avatar asked Jul 24 '26 00:07

dav


1 Answers

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;
    }

}
like image 167
drmonkeyninja Avatar answered Jul 28 '26 04:07

drmonkeyninja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!