Using CakePHP model class - php

I'm just studying CakePHP so sorry for any obvious mistakes.
I have created model class and changed default table name.
class Weathers extends AppModel {
public $tablePrefix = 'weather_';
public $useTable = 'forecasts';
function saveCountries($countries){
...
}
}
And my controller function
if (!$this->loadModel('Weather'))
exit;
$Weather = $this->Weather;
$Weather->saveCountries($countries);
I'm getting error on $Weather->saveCountries($countries);
Error: Table weathers for model Weather was not found in datasource
default.
Please help find out what I do wrong.

The Model class you defined is Weathers not Weather. So just change the class name Weather instead of Weathers and this is done.

Note the declaration of your Model class.
You've called it Weathers.
There is no problem with this. However, as you are trying to then load the model Weather (not the lack of plural in this case) CakePHP is constructing a model dynamically for you, instead of using your Weathers (plural) class.
The CakePHP standard is to use a singular name for models. I suggest that you rename your model class to Weather to avoid this issue. Once you make this change, the code that you have for loading the model will work as intended.

Related

naming convention of table, model file and model class in cakephp

I am using cakephp 2.6.9. I have a table named: chat_info and model file: ChatInfo.php and class inside ChatInfo:
<?php
/**
*
*/
class ChatInfo extends AppModel
{
var $name = "chatinfo";
}
?>
but it shows an error. I searched for this error and found that this is due to naming convention violation in cakecaphp. But whats wrong am I doing here
Model::useTable
As found in the docs:
The useTable property specifies the database table name. By default, the model uses the lowercase, plural form of the model’s class name
Conventions are not intended to be unbreakable rules. They are guidelines which, if followed, make life easier. That does not mean they have to be followed. Using useTable it's possible to use any table name, in this case:
class ChatInfo extends AppModel
{
public $useTable = "chat_info";
}
Two asides, assuming you're not actually using php4:
It is a terrible idea to set the model name to something other than the actual model name. It's not necessary to set it to anything, since it's designed purpose is php4 compatibility. The name of a model is the class name, setting it to something else can easily lead to confusion or unexpected side effects.
Declaring variables with var is php 4 style, use the features of the version of php in use, i.e. declare variables using public, protected or private.
if you will rename the table from chat_info to chat_infos it will be ok
Or if you want to mantain that name for the table then add this in your model:
$useTable = 'chat_info';
and your model will be associated to the table chat_info (without plural mode)

how to create multiple models against multiple function in single controller in CakePHP

i think, In "CakePHP" one model is against each controller but i have multiple functions in single controller and each function represent different page and database table.
i.e
public function manage_categories(){}
public function manage_sub_categories(){}
above 2 functions are in Admin Controller but now the issue is how to create model against each function to represent database. each function has unique attributes in database.
One thing more either model name should be same to controller name "admin" or this name will be same as functions name. while in normal circumstances model name is same to controller name.
"Users" model name is used against "UsersController"
kindly guide me ti resolve above said issue. i tried enough to solve it bot couldn't.
Thanks in advance.
If you have two database tables it would be logical and best practice in terms of SoC to have two controllers instead of throwing a lot different things that don't belong into the same domain into a single controller.
Sometimes when you just want to use a part of data from an associated model you can access it through the associations:
$this->Model->SubModel->foo();
Also you say you have an admin controller which is a working but not very good approach. Instead CakePHP features prefix routing. So an action accessed like /admin/categories/some_action will route to the CategoriesController some_action() action.
"Users" model name is used against "UsersController"
Is wrong, by convention models should be named singular, not plural. Your UsersController won't find an Users model because it's looking for an User model.
And stay away from Model::query(), use the ORM instead as much as you can.
public function manage_categories(){}
public function manage_sub_categories(){}
Should become:
class CategoriesController extends AppController {
public function admin_index() { /*...*/ }
}
class SubCategoriesController extends AppController {
public function admin_index() { /*...*/ }
}
But assuming that sub-categories belong to a category which is the same table I don't see a need for a second model or second controller at all.

Database Table custom naming convention Laravel Eloquent

I'm trying to retrieve data from a table called completion_date using Eloquent. My Model name is Completion and as per laravel documentation, i should declare a (protected) table name or else Eloquent will use 'completions' as the default table name. So i did this declaration.
I'm getting problems with my Controller since i dont know which name to use to refer to my Model when i'm making the View. I'm getting an InvalidArgumentException that View [completion.lsz] not found. if i just use my model name to make the View.
Error:
InvalidArgumentException thrown with message "View [completion.lsz] not found."
Can someone pls help out?
Model
<?php
//Model (file name: Completion)
class Completion extends Eloquent{
protected $table = 'completion_date';
public $timestamps = false;
}
Controller
class CompletionController extends BaseController {
public function index() {
$lsz = Completion::all();
return View::make('completion.lsz', ['completion' => $lsz]);
}
}
Route
Route::get('/Completion', 'CompletionController#index');
View names in Laravel work like a path. The . gets converted to a /
That means, your view resolves to the file app/views/completion/lsz.blade.php (or app/views/completion/lsz.php without Blade)
So you either have to change the name of your directory in the views folder to "completion" or change the view make command to:
View::make('lsz.lsz', ['completion' => $lsz]);
The error message says that the view file completion/lsz.blade.php was not found.
It's not related to the model or database.

Cakephp using model wtihout defining model file

I am new to cakephp and trying to customise a cake application.
I have seen they are using models without having model class files in app/models folder
I think there is an automatic mapping from table to model
I am sharing some usefull lines of codes
public $uses = array('LinkEmperorCampaignDetail','Configuration','Article');
$this->paginate = array(
'conditions' => $condition,
'limit' => 10
);
$this->set('articles', $this->paginate('Article'));
As you have seen its importing Article model using $uses variable, there is a table "articles" in database, But there is no file Article.php in app/models. I have deleted cache folder and disabled caching.
I have checked if it is automatic, by creating a table "test" and used this code
$test=$this->test->find('all');;
var_dump($test);exit();
but getting this error Error: Call to a member function find() on a non-object
Please let me know how this is happening
Thanks,
Lajeesh
Change it to:
$test = $this->Test->find('all');
Also, please, check cakephp model and database conventions
Model files are optional
Cake will user an AppModel instance if there is no model file found:
CakePHP will dynamically create a model object for you if it cannot find a corresponding file in /app/Model.
As such a reference tothis->Article will be an instance of AppModel as the model is declared in the $uses variable but a model file doesn't exist.
That doesn't mean $this->RandomModel works
Referencing a random model, as seen in the question, will simply produce the following error:
Call to a member function find() on a non-object
That's to be expected because the controller knows nothing about the Test model from the code in the question.
The optional model file handling does not mean that you can reference any model by expecting it to exist as a Controller class property. $uses exists for the purpose of telling the controller which models it needs to know about. If a model is only needed in specific circumstances, loadModel exists for this purpose:
$this->loadModel('Test');
$stuff = $this->Test->find('all');

Load CodeIgniter models in Controller constructor

Coming from C#/.NET MVC 3/4, I'm not really used to CodeIgniter's implementation of models.
The documentation shows models being loaded within controller methods, however I'm using the model in almost every method and my model is storing data used across its methods in properties via its constructor.
Is there any reason NOT to instantiate the model in the controller constructor that I'm overlooking?
You can load model as per following ways also :
means if you have your model in any folder so using following code you can load model in controller.
$this->load->model('modelFolder/' . $this->controller . '_model');
For eg. :
if you have your model in folder named "modelFolder" then do like this :
class demoController extends CI_Controller {
var $controller = "user";
/* Local Constructor Will Be Overriding The One In The Parent Controller Class So We Need To Manually Call It. */
public function __construct() {
parent::__construct();
$this->load->model('modelFolder/' . $this->controller . '_model');
$this->load->model('common_model');
}
}
Hope it will help you...
There is no reason not to load the model for every controller activation. It could even be put in the configuration's autoload for all controllers.
The only reason not to always load it would be if many operations do not need the model. Then you could save a little bit of memory and time.

Categories