PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, January 26, 2022

[FIXED] Cakephp 3 - reusable code for Table Entities

 January 26, 2022     cakephp, cakephp-3.x     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing