How does cakePHP naming convention work? - cakephp

I'm relatively new to PHP. Started learning PHP, but then come across cakePHP, which is suppose to speed up development time.
After reading the documentation and blog tutorial I still don't understand the naming convention. I guess I won't know until I start to do some examples, but to get me started can someone please explain to me how cakePHP associate database tables to the controller/model layer?
The below code is an abstract from the tutorial. It is a controller method that passes the post id to the view layer. The database table is called "posts". $this->Post refers to the model class of Post, which correlates to the plural form of posts in the database.
public function view($id = null) {
$this->Post->id = $id;
$this->set('post', $this->Post->read());
}
OK I get that. Then, in the documentation it refers to the following correlation:
ReallyBigPerson and really_big_people
So it seems like the correlation actually follows the rule in English semantics. Does this mean that cakePHP has a list of singular and plural words hidden somewhere that it works from? For example can I use the below correlation without breaking the code?
This and these or Man and men or Foot and feet or Moose and moose or Goose and geese
Furthermore, if I have both singular and plural form of tables in my database, will it break the code, or will it just associate to the plural-formed table?
Just find it baffling... Why couldn't they just match the naming convention like for like with prefixes?

Inflector
CakePHP uses its Inflector class to determine the plurals of things.
Since the naming conventions dictate that model names are singular and tables names are pluralised, it uses the inflector to apply English semantics / rules to determine the plural.
If you need some help understanding the output of the Inflector, you can use the CakePHP inflector website.
Pluralisation Examples
Model name: Post
Table name: posts
Model name: User
Table name: users
Model name: Sheep
Table name: sheep
Model name: News
Table name: news
Model name: Radius
Table name: radii
Check the Inflector site to be sure.
Non-standard Table names
While CakePHP offers a standard rule set for naming and conventions, none of it is set in stone. If you want to change the name of the table used for a particular model, simply specify the table name in the model:
class Thing extends AppModel {
public $useTable = 'somethings';
}
Or, if you want a model that does not use a table:
class Post extends AppModel {
public $useTable = null;
}

Related

wagtail: How to make bidirectional page model relations?

I am looking for a way to implement bidirectional m2m models in wagtail.io.
One author can write multiple posts and
one post can have multiple authors.
I can set/unset a relation between the two models both on the author page and on the post page
A relation set on the Author page shows on the Post page and vice versa.
In Django Admin I solved this using the normal filter_horizontal m2m widget and a custom through parameter:
models.py:
class Author(models.Model):
posts = models.ManyToManyField('app.Post', blank=True, through=Post.authors.through)
class Post(models.Model):
authors = models.ManyToManyField('app.Author', blank=True)
I stumbled upon an approach that at least enables a one-way relation using inlines however I cannot see how to turn this around to solve my bidirectional problem.
This is how far I got in wagtail:
In models.py class PostPage(Page) I defined an InlinePanel:
InlinePanel('related_agents', label="Related Agents"),
and then further down a custom through model (compare to this blog post):
class PostPageRelatedAuthorItem(Orderable):
page = ParentalKey('PostPage', related_name='related_authors')
# one-to-one is the same as ForeignKey with unique=True
author = models.OneToOneField('thoughts.AgentPage')
panels = [
PageChooserPanel('author', 'app.AuthorPage'),
]
Is there a bidirectional way and if yes could you help me along with some hints - many thanks in advance.
Because of some restrictions around django-modelcluster you can't use M2M fields with Wagtail. You have to specifically setup the "through" model basically.
You can find all the info you need here http://www.tivix.com/blog/working-wagtail-i-want-my-m2ms/

Django, relate User with another table

So I got the tables you can see in the image below:
.
What I would like to do is to create a relationship so that each user (of django auth_user) will be enrolled(or able to enrol) to exactly one "course" so that he will be able to see next events for his modules.
Do I have to create another table and place 2 foreign keys or this is a way to do it in 'php' and it's more simple with Django? I was suggested to create 'student' model inheriting from 'User' with extended behavior and one to many relationship on auth. I tried to do that but unfortunately had not results since I'm really new to Django & Python.
If every auth_user (or auth.User) will be or have the opportunity to be enrolled on a course I would create a 'user profile' model that has a 1-to-1 relationship with the django User model. You can store additional User data in this model, including what course they are enrolled on. See https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model for more details but here is an example:
class UserProfile(models.Model):
user = models.OneToOneField('auth.User')
course = models.ForeignKey('courseapp.Course', null=True)
You would probably need to create a signal that gets fired each time an auth.User object is saved, such that if it is the first time that User object has been saved, it automatically creates the UserProfile:
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from yourusersapp.models import UserProfile
def create_user_profile(sender, instance, created, **kwargs):
# Automatically creates a UserProfile on User creation.
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
When you query a User object, you can then reference the User object's profile like:
user_object.userprofile
You could then create a Course object and link the user_object indirectly via its UserProfile to that Course:
course = Course.objects.create(name='course_name', next_field='whatever')
user_profile = user_object.userprofile
userprofile.course = course
userprofile.save()
Now you have a user object with a UserProfile that is linked to only 1 course. Many users can be on the same course, but a user can only be on 1 course. You can also reference all users on a particular course like:
course = Course.objects.get(name='course_name')
course_users = course.userprofile_set.all()
HTH
I think that you can go about this one of two ways.
Extend the User model. 'Student' would probably be a good name for your new model. It would have a OneToOne relationship with 'User', and a ForeignKey relationship with 'Course'. It can store any other information that is applicable to students only. Documentation for how to do that can be found here https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#extending-the-existing-user-model
Create a custom User model that has a ForeignKey relationship with Course. This approach is a bit more complicated, but yields a slightly cleaner end result. Documentation for that is here. https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#substituting-a-custom-user-model
Sorry if it seems like I'm just sending you to the Django docs, but both of those sections are well written and should explain things pretty clearly. If you'd like to post another question with example code we can try and see why your original attempt at extending the User model didn't work. By the way, your "Student" model shouldn't have to inherit from the User model in order to extend it.

How to use Yii with a multilingual database model?

I’m having a problem getting the data from my database which I created to be completely multilingual, and I hope someone here can help me.
I’ve split up all my tables in 2 parts; the “universal” table (does not contain any text that needs to be translated) and the table which contains all the fields that need to be translated with their translations.
Example tables:
base_material
id
picture
base_material_i18n
base_material_id
localization_id
name
description
review_status
review_notes
localization
id
language_name
Query to get the translations (using English (en) as a fall-back language if there is no translation available):
SELECT o.id
, o.type
, o.code
, o.position
, ifnull(t.name,d.name) name
, ifnull(t.description,d.description) description
FROM base_material o
INNER JOIN base_material_i18n d
ON ( o.id=d.base_material_id)
LEFT OUTER JOIN base_material_i18n t
ON ( d.base_material_id=t.base_material_id AND t.localization_id='nl' )
WHERE d.localization_id='en'
My question is how I can automatically get those translations (with the fall-back language as in this query) attached to my model in Yii when I’m searching for the base_material objects? (This is only 1 example table, but almost all my tables (20+) are built in this way, so if possible I would be needing something flexible)
An example of an existing system using what I would need is Propel: http://propel.posterous.com/propel-gets-i18n-behavior-and-why-it-matters
Any ideas how to go about doing that? I’ve checked the existing Yii extensions regarding multilingual sites (like Multilingual Active Record), but they all use a different database design (general information+fall-back language in the main table, translations in the i18n table), and I’m not sure how to change those extensions to use my kind of DB model.
If someone knows of a way to change that existing extension so it can use my kind of DB scheme, then that would be absolutely brilliant and probably the best way to do this.
Edit: I've added a bounty because I still can't find anything on how to let Propel work with Yii (there does exist an extension for Doctrine, but Doctrine doesn't support this kind of DB model with translations either), nor any more information as to how to deal with this using an existing Yii extension or with scopes.
Edit: 98 times viewed but only 3 upvotes and 1 comment. I can't help feeling like I'm doing something wrong here, be it in my question or application/database design; either that or my problem is just very unique (which would surprise me, as I don't think my multilingual database design is that absurd ;-). So, if anyone knows of a better all-round solution for multilingual sites with Yii and/or Propel (apart from the current extensions which I really don't like due to the duplication of text fields) or something similar, please let me know as well.
Thanks in advance!
Have you tried http://www.yiiframework.com/extension/i18n-columns/ (based on http://www.yiiframework.com/extension/stranslateablebehavior/)?
It is an alternate, simpler, approach by adding new table fields in the style of {field}_{language code}, and then setting the translated field in the original model to the current language's translation on afterFind.
In essence, it will get you up and running with translatable fields with the translated content being fetched "automatically", for good and bad :). Adding and removing languages (=columns) is done using migrations.
I am also looking for a generic solution to implement i18n into Yii models.
Recently I chose a very similar database schema for a project like you.
The only difference is, that I am not using a separate language table, I store the language information in the i18n table.
The following solution is without a custom SQL statement, but I think this could be implemented with relation params, anyway, if you're working with foreign key in your database (eg. MySQL InnoDB) gii will create relations between your base_material and base_material_i18n table, like
class BaseMaterial extends CActiveRecord
public function relations()
{
return array(
'baseMaterialI18ns' => array(self::HAS_MANY, 'base_material_i18n', 'id'),
);
}
class BaseMaterialI18n extends CActiveRecord
public function relations()
{
return array(
'baseMaterial' => array(self::BELONGS_TO, 'base_material', 'id'),
);
}
Now you'd be able to access your translations by using the object notation for relations.
$model = BaseMaterial::model()->with('baseMaterialI18ns')->findByPk(1);
foreach($model->baseMaterialI18ns AS $translation) {
if ($translation->language != "the language I need") continue:
// do something with translation data ...
}
I thought about creating a behavior or base class for those models which would act a as helper for managing the translations - pseudo code:
I18nActiveRecord extends CActiveRecord
protected $_attributesI18n;
// populate _attributesI18n on query ...
public function __get($name) {
if(isset($this->_attributesI18n['language_I_need'][$name]))
return $this->_attributesI18n[$name];
else if(isset($this->_attributesI18n['fallback_language'][$name]))
return $this->_attributesI18n[$name];
else
parent::__get();
}
CActiveRecord __get() source
There is more work to be done to find the needed i18n record, also you could further limit the with() option to improve performance and reduce parsing on the PHP side.
But there may be different use cases how to determine the value, e.g. all translations, translation or fallback, no fallback (empty value).
Scenarios could be helpful here.
PS: I would be up for a github project!
You can try to use a simple multilingual CRUD extension.
it is very simple to use and modificate. you just need to add language field to your table.
just watch description here: http://all-of.me/yii-multilingual-crud/
it is in alpha state, but tried on a few projects. you can easily modificate it or contact author to fix or add features

Custom South migration with custom fields - Django

I am pretty new to Django and just got a job that involves maintaining and adding features to a site I did not design, so I am still kind of confused about the structure and what not of the project. The site is using South for database migrations and I've got a hang of using it to add new applications to the project. The trouble I am having now is that I need to delete a certain field in a model because it is no longer needed and on the admin page it is required to be filled out. From my understanding of Django so far it appears to be a custom field. It is defined like this in its own separate library application(still not sure if thats the right lingo).
class Genre(models.Model):
name = models.CharField(max_length=255)
def __unicode__(self):
return u"%s" % self.name
Here is the models that uses the custom field if that helps out any.
class Entry(models.Model):
artist = d51fields.ForeignKey(Artist, instantiate_fn=instant_artist)
album = d51fields.ForeignKey(Album, js_methods=['match_artist_and_startswith'], instantiate_fn=instant_album)
track = d51fields.ForeignKey(Track, js_methods=['match_album_and_startswith'], instantiate_fn=instant_track)
genre = models.ForeignKey(Genre)
submitted = models.DateTimeField(auto_now_add=True)
is_rotation = models.BooleanField()
dj = models.ForeignKey(DJ)
show = models.ForeignKey(Show, null=True, blank=True)
objects = EntryManager()
def __unicode__(self):
return "%s [%s]" % (self.artist, self.track)
class Meta:
verbose_name = "entry"
verbose_name_plural = "entries"
I've looked at the documentation for migrating custom fields but it is all really confusing for me, so I am looking for some more help. I just want to get rid of the table holding the Genre field and clean up the dependencies with the foreign keys associated with it. Do you think I should write some custom rules for South and use a migration or just try and do it manually in Postgresql. I tried doing it with just Postgres and I failed miserably.
Any guidance would be greatly appreciated. If you want more info about the situation just ask and I can add it to the post. I have a feeling there is a lot of dependencies I will have to deal with, but hopefully there is a simple fix.
Also if some one knows how to get a good view of the database structure that would be great.
Thanks so much. All of you guys are great.
Edit1
Here what I got when I removed the ForeignKeys and then ran
manage.py schemamigration logs --auto
! Cannot freeze field 'logs.entry.artist'
! (this field has class d51_admin_autofk.fields.ForeignKey)
! Cannot freeze field 'logs.entry.album'
! (this field has class d51_admin_autofk.fields.ForeignKey)
! Cannot freeze field 'logs.entry.track'
! (this field has class d51_admin_autofk.fields.ForeignKey)
! South cannot introspect some fields; this is probably because they are custom
! fields. If they worked in 0.6 or below, this is because we have removed the
! models parser (it often broke things).
I am not totally sure what sort of action I should take next. I looked into the South documentation and it wasn't too clear about how to write the rules for migrating things like this.
I don't see any custom field anywhere in the code you posted. All I see is two models, all containing standard fields shipped with Django.
If I understand correctly, you can just delete all ForeignKey references to your Genre model. Then run ./manage.py schemamigration <yourappname> --auto. This will ask you for a default value for the genre field in the Entry model, provide an ID of some kind. (This is because migrations can be applied both forwards and backwards, so if you try to undo the migration, this is the value that will get inserted in all your model instances.)
Finally, just applying the migration should make it happen: ./manage.py migrate <yourappname>.
After that you should be safe to drop the table storing your Genre model.
Be sure to try this on a development server though, just to make sure it doesn't blow up. (-;

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