Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP call to member function on non-object

Tags:

cakephp

I have the following Model and Controller files, and when i visit this url, http://....../pois/index i get this error:

Notice (8): Undefined property: PoisController::$Poi [APP/controllers/pois_controller.php, line 5]

Fatal error: Call to a member function find() on a non-object in /home/joecoyle/public_html/app/controllers/pois_controller.php on line 5

The Model is this, called poi.php:

<?php
class Poi extends AppModel {

}
?>

And the controller is this, named pois_controller.php

<?php
class PoisController extends AppController {

    function index(){
            $this->set('pois',$this->Poi->find('all'));
    }
}
?>

As i am new to CakePHP i am not sure what is causing this error, as everything seems to be named, right, and i am following the tutorial on the CakePHP site...

Thanks

like image 240
joec Avatar asked Dec 07 '25 06:12

joec


2 Answers

You need add var $name = "Poi"; to initialize your class in the controller.

And I've tested that in PHP5.It seems that this is necessary.

Edit: controller file name:pois_controller.php,code:

 <?php
 class PoisController extends AppController
 {
       var $name = "Poi";
       function index()
       {
           debug($this->Poi);
           exit;
       }
 }
 ?>

database name:pois.Structure:id ,name

And using /pois/ will got:

Poi Object
(
[name] => Poi
[useDbConfig] => default
[useTable] => pois
[displayField] => name
[id] => 
[data] => Array
    (
    )

[table] => pois
[primaryKey] => id
[_schema] => Array
    (
        [id] => Array
            (
                [type] => integer
                [null] => 
                [default] => 
                [length] => 11
                [key] => primary
            )

        [name] => Array
            (
                [type] => integer
                [null] => 
                [default] => 
                [length] => 11
            )
   ...etc
like image 57
Young Avatar answered Dec 08 '25 22:12

Young


If SpawnCxy's solution doesn't do the job (my own controllers set the name property to the pluralized version rather than the singular variation that the model takes), take a look at the inflection. "Poi" isn't a "common" word and a quick test tells me that CakePHP 1.2.6 doesn't handle this word the way you're thinking it will:

echo '<p>' . Inflector::singularize( 'Pois' ) . '</p>'; # prints "Pois"
echo '<p>' . Inflector::pluralize( 'Poi' ) . '</p>';    # prints "Pois"

The point of this, of course, is that Cake may not be making the correct association between the PoisController (plural) and the Poi model (singular) the way it does for most common English names.

like image 37
Rob Wilkerson Avatar answered Dec 08 '25 23:12

Rob Wilkerson



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!