Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kohana 3 Auto loading Models

I'm attempting to use a Model but I get a fatal error so I assume it doesn't autoload properly.

ErrorException [ Fatal Error ]: Class 'Properties_Model' not found

The offending controller line:

$properties = new Properties_Model;

The model:

class Properties_Model extends Model
{
    public function __construct()
    {
          parent::__construct();
    }

}

I also put the class in three different locations hoping one would work, all there failed. They are: application/classes/model application/model application/models

What am I missing?

like image 276
pigfox Avatar asked Feb 26 '23 23:02

pigfox


2 Answers

Ah, I got this question emailed directly to me (via my website's contact form)!

Here is what I responded with (for the benefit of other people which may run into this problem).

The correct location of a model named properties is

application/classes/model/properties.php

and the class definition would be as follows

class Model_Properties extends Model { }

Think of the underscore above as the directory separator. That is, if you replaced the underscore with a / you would have: 'model/properties', which will be your file under application/classes.

To load the model from a controller, you can use PHP's standard new operator or do what I prefer, which is

$propertiesModel = Model::factory('Properties');

I'm not 100% why I prefer this way... but it works for me :)

like image 145
alex Avatar answered Mar 23 '23 23:03

alex


First off, The Kohana 3 fileyestem does not work like Kohana 2's!

In K2 the autoloader looks at the class name searches for the class in different folders, based on the suffix of the class.

In K3, class names are "converted" to file paths by replacing underscores with slashes.

i.e. Class Properties_Model becomes classes/properties/model.php

As you can see, using a Model suffix in this new system won't really help to group your models, so basically you prepend "Model" to the class name instead of suffixing it:

Model_Property is located in classes/model/property.php

For more information see the Kohana 3 userguide

like image 40
Matt Avatar answered Mar 23 '23 22:03

Matt