cakephp 2.10 get data without model class - cakephp

Cakephp 2.10 ?
$text = $this->PrivacyPolicy->find('all', array(
'fields' => array('id', 'title', 'description')
));
How PrivacyPolicy is becoming a model role as there is no Model class in the files or relation with the database ?

Magic and unicorn dust... otherwise known as naming conventions and auto-models.
If no concrete model class can be found, CakePHP will create an instance of the AppModel base class instead, which will lookup the database table based on the the model name that you've used. So in your case the AppModel instance will look up the data in privacy_policies (lowercased, underscored, plural variant of the model name).
Quote from the docs:
CakePHP will dynamically create a model object for you if it cannot find a corresponding file in /app/Model. This also means that if your model file isn’t named correctly (for instance, if it is named ingredient.php or Ingredients.php rather than Ingredient.php), CakePHP will use an instance of AppModel rather than your model file (which CakePHP assumes is missing). If you’re trying to use a method you’ve defined in your model, or a behavior attached to your model, and you’re getting SQL errors that are the name of the method you’re calling, it’s a sure sign that CakePHP can’t find your model and you need to check the file names, your application cache, or both.
https://book.cakephp.org/2/en/models.html#understanding-models

Related

cakephp3 iterate hasMany associated entities

We are using the new cakePHP ORM and I have some issues understanding the way the new ORM works when dealing with hasMany associations.
E.g. We have a Table called "Users" which has a hasMany relation to another Table "UsersAbsences". The definition and handling itself works fine. We have defined the Table-Objects and the Entities.
$this->addAssociations([
'hasMany' => [
'UsersAbsences' => [
'className' => 'UsersAbsences',
'propertyName' => 'absences',
'foreignKey' => 'user_id'
]
]);
Within our UsersTable we've created a custom method which retrieves details to one User, using the QueryBuilders ->contain Method to fetch the hasMany-associated "UsersAbsences" defined by property "absence". We're setting the view-variable $user to work with the Entity in the template: Works fine.
...
$users->contain(['UsersAbsences',...]);
...
Now the part that puzzles me:
The Object-type of $user is "UserEntity". When I now iterate through the $user->absences... i always get CakeEntity objects, not (as I would expect) AbsenceEntity-objects.
Problem: I would like to implement a custom method in the UserAbsence-Entity which I would like to call in the template when iterating through each Absence of the user.
When using the ->contain Method for associations attached with "belongsTo", I get the correct Entity-Class.
Someone an idea how to deal with that?
Mind your terminology, entity classes do not have a Entity suffix, this makes your question a little confusing, as one might think that you've named all your classes incorrectly! Please use actual, ideally fully qualified classnames in your questions!
That being said, by default the name of the corresponding entity is figured from the table class name, that is, the singular name without Table suffix. So, for UsersTable it's User, and for UsersAbsencesTable it would be UsersAbsence, not just Absence.
So, renaming your Absence entity file/class to UsersAbsence should fix the problem. Alternatively you can manually define the entity class a table should use by specifying it via Table::entityClass().
See also
Cookbook > ... CakePHP Conventions > File and Class Name Conventions
Cookbook > ... ORM > Table Objects > Customizing the Entity Class a Table Uses

Unable to access model in plugin

I have two Plugins in cakephp both contains User model. When I want to access the properties of User model it always call first User model. How can I access second User Model?
Not possible - rename your models
Unfortunately that's not possible. Because of the way models are defined, that means you're wanting to load two different classes with the same name in the same namespace (global) which is not possible with PHP - the only solution is to use different classnames.
A standard practice is to name plugin classes prefixed with the plugin name to avoid collisions:
So for example in the foo plugin:
<?php
//App/Plugin/Foo/Model/FooUser.php
class FooUser extends FooAppModel {
}
And in the bar plugin:
<?php
//App/Plugin/Bar/Model/BarUser.php
class BarUser extends BarAppModel {
}
This does lead to slightly more cumbersome usage, but prevents roadblock-problems when trying to access both classes at the same time.
You have to specify the plugin name when you initialize the model classes. So you could call your first one 'User' and your second one 'PluginUser', ie:
$this->User = ClassRegistry::init('PluginOne.User');
$this->PluginUser = ClassRegistry::init('PluginTwo.User');

CakePHP model named 'Model' not working

I have a model named Model. After some frustration with its responses, I came to the conclusion that the class file is not being used.
To test this, I changed the name of the file from model.php to model_x.php and no errors were encountered.
Can someone verify to me if Model is an invalid name for an appModel class?
I am using CakePHP 2.x
Lee
The class Model is already taken
So what you should do is create another name. It's the same when using a controller and model named layout, because the Layout folder in View is already used for the layouts. So you should either come up with a clever solution with routing, or simply give it a different name.

Howto extend a plugin model class in CakePHP with "clean" classnames?

I'm currently learning CakePHP. I use CakePHP 2.2.3. I have succesfully "installed" a user management plugin. This plugin has a model class "User" and uses table "users". Now, I'd like to extend this User model in order to e.g. relate my own models to it, e.g. Posts.
I managed to to this with the following code:
App::import('Model', 'Usermgmt.User');
class MyUser extends User {
var $hasMany = array('Post');
var $useTable = 'users';
}
This works.
However, I don't like the fact that I have to call my Model class something like "MyUser". It makes everything very ugly and, maybe - theoretically - sometime I want to install another plugin that uses classname "MyUser". Is it somehow possible to use "clean" class names and prevent possible name collisions in the future..?
No, that's not possible because CakePHP doesn't yet support namespaces. According to the roadmap support for namespaces is planned for CakePHP 3.

What are the reserved database table names in CakePHP?

I was planning my database and since CakePHP hasn't named its classes with its own prefixes, there are many classes that may collison with model classes created according to naming conventions.
So my question is in three parts:
Is there a list of database
table names that are reserved or a
simple way to check if it is? It
would be a pain if I plan database
with 100 tables and notice some of
the tables and their connections would
have to be renamed...
Is there a simple way around it without breaking any CakePHP magic? Is it adviced? Would naming the tables in other way by adding own prefix 'my_' or similar at the beginning of table name the best way?
Is namespaces or something similar coming to
CakePHP version 2 that would allow
use of all kinds of table names?
No, there aren't. Cake doesn't care what you name your tables as long as you adhere to Cake's naming conventions. It generates the schemas it uses for magic model methods the first time a model/s is loaded by a controller; you don't have to lift a finger. See http://book.cakephp.org/view/903/Model-and-Database-Conventions
Best advice: don't fight Cake on this. If you really cannot adhere to to Cake's conventions, you might as well not use Cake; it's stupidly difficult, confusing and succeeding just means you've lost most of Cake's heavy lifting abilities. Pluralizing your table names isn't THAT bad, and Cake will be happy.
This functionality is already available in 1.3 - name your tables anything that pleases you (as long as they're plural words.)
-- You'd probably be well-served to check out baking apps in the console so you can get familiar with what Cake wants to see and how it works on different table layouts.
Edit after clarification:
Your models, controllers, and view directories all share a common name, like so:
// in /app/models/rate.php
class Rate extends AppModel {
var $name = 'Rate';
// in /app/controllers/rates_controller.php -- note the underscore
class RatesController extends AppController {
// controllers are capitalized + plural
var $name = 'Rates';
// in /app/views/rates/*.ctp - Cake's magic autoRender expects to find a view file with
// the same name as the action rendering it - the view for Rates::index() is index.ctp
All of your models extend cake's AppModel class (which extends cake's Model class), no prefix needed. All controllers will extend Cake's AppController class - the class name is suffixed with Controller, and the file name is suffixed with _Controller.
You'll fine AppModel and AppController in /app, and they exist expressly for whatever app-wide custom methods / properties you may have. Since all of your models / controllers extend them, inheritance automatically disperses whatever properties / methods you place in them - for example, Auth. ^_^
But you can still name a table Models, or Controllers, or Views, or whatever, I guess. The $name property is an alias; you can create multiple instances of the same table in the same model by aliasing it with a different name. You can create models without tables, and you can switch between multiple tables - or databases, or servers - in a single model. You can also create non-database-type data objects (such as flat xml files) for your models. Dynamically named classes / methods ($$Model::save(), etc) are what's running under the hood anyway. I've done something similar in iterations for the sake of DRYing up my app and I didn't have a problem. (Although I personally doubt actually pulling off a local model named Model would be worth the effort you'd put into the experiment...)
And on that note, Cake's API spells out all it's classes their methods, etc. (generates off the comments in the codebase):
http://api13.cakephp.org/classes
HTH. :D
I know from experience you can't use table names like 'files' and 'models' because they create classes that are already used by Cake for other things such as File and Model.
I haven't come across any other problems like this but I'm sure they are there to be found.
I would suggest avoiding the use of any name used by cake core classes.
I know this is a bit of an old thread but just came across it searching for something else. I think this shoud help answer question #2. In database.php you can add your db table prefix in the DATABASE_CONFIG class /app/config/database.php. See the last key in the config array below:
var $default = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'user',
'password' => 'password',
'database' => 'database_name',
'prefix' => '',
);

Resources