Search code examples
phpcakephpcakephp-3.0camelcasingcakephp-3.8

Implement tables with error underscores: Fatal error: Call to a member function


when I implement a table with the name example_a call:

  • model/entity: ExampleA.php
  • model/table: ExampleATable.php
  • controller: ExampleAController.php
  • Template/ExampleA: index.ctp

gives me the following error:

Notice (1024): Undefined property: ExampleAController :: $ ExampleA in C: Program Files …

Fatal error: Call to a member function find () on boolean

to print the list of objects in the controller implement a function:

 public function index ()
 {
     $This->set('examples',$this->ExampleA->find('all'));
 }

I specify that this table has no relationship whatsoever with other tables

if instead I do the same thing implementing a table without underscore it works


Solution

  • The main issue here is that you have deviated from the CakePHP conventions, which is fine, but means you need to do some extra work.

    The first thing to do is tell the framework what your Table and Entity classes are called. In your ExampleATable.php file in the initialize() method, you need to set the table, entity and other things.

    <?php
    public function initialize(array $config)
    {
        $this->setTable('example_a');
        $this->setAlias('ExampleA');
        $this->setEntityClass(\App\Model\Entity\ExampleA::class);
        //etc
    

    Secondly, in your controller, we'll need to manually load the Table class, as it doesn't match the controller.

    // Get or create a table instance
    $ExampleATable = $this->getTableLocator()->get('ExampleA');
    
    // Use the table instance to query
    $query = $ExampleATable->find();