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

Friday, December 31, 2021

[FIXED] How to extend entity classes with custom functions (business logic) in cakephp v3

 December 31, 2021     cakephp, cakephp-3.0     No comments   

Issue

In cakephp 3 (3.3.5, that is) I want to extend my entity classes with custom functions (business logic). For example:

namespace App\Model\Entity;

use Cake\ORM\Entity;

class Something extends Entity {
    public function isFoo() {
        return true;
    }
}

The corresponding table object looks like this:

namespace App\Model\Table;

use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\ORM\TableRegistry;
use App\Model\Entity\Something;   // produces an `unused import' warning

class SomethingsTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);
        ...
    }

    ...
}

In the controller, I use this code to retrieve the entity from the database and call the custom function:

class SomeOtherController extends AppController {
    ...
    $this->loadModel('Somethings');
    $thing = $this->SomethingsTable->get($id);
    if ($thing->isFoo()) { ... }
    ...
}

However, this fails with a fatal error:

Error: Call to undefined method Cake\ORM\Entity::isFoo() 

Note, when I do a

<?= var_dump($thing,true); ?>

in the corresponding view, $thing is shown as of type Cake\ORM\Entity.

How can I change the table's get() function to return entities with the correct type "Something" ?


Solution

It should be:

$thing = $this->Somethings->get($id);

// not 
$thing = $this->SomethingsTable->get($id);

Thats why the Something entity is not used, but the default Entity class.

CakePHP autotables, since it can not find the SomethingsTableTable the default table class is used. Therefore also the default entity class is loaded. If your test method would contain a query to the db, there would have been an error thrown, saying that somethings_table does not exist.



Answered By - Tolga
  • 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