Wednesday, January 26, 2022

[FIXED] Cakephp 3 - reusable code for Table Entities

Issue

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


Solution

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

}


Answered By - drmonkeyninja

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.