model

Traits

Traits are a powerful feature in PHP that allow developers to reuse sets of methods in multiple classes without relying on traditional inheritance. In languages with single inheritance (like PHP), a class can only inherit from one parent class. This can sometimes be limiting when you want to share functionality across multiple, unrelated classes. Traits solve this problem by letting you "mix in" methods into different classes.

Behaviors

Behaviors are ways to enable the reuse of Model functions. For example, instead of adding our slug creation function into every model, which could be a lot of redundant code, we can create a Behavior to encapsulate the code and add the Behavior to our Model's initialize(), just like the Timestamp Behavior.

Unique Slugs

In our Database and Model tutorial we covered a very simple example to create a slug for use with a record. One problem with this example is that it doesn't create unique slugs, and since our database requires unique slugs, this could become an issue with two users having the same first and last name.

Neighbors

In CakePHP 2 there was a handy feature called "neighbors" where you could simply request the neighboring records (previous and next) for easy linking. This is not present since CakePHP 3, possibly due to the limited use of such a feature, however, with custom finders you can replicate the functionality yourself.

Table Relationships

When working with CakePHP it is important to remember "Convention over Configuration." If you start from the bottom, or back end, the database, and work your way forward correctly, CakePHP will do much of legwork for you, saving you tons of redundant and repetitive work.

If you don't, there are almost always ways to make things work the hard way. An example of this is the relationships between tables. If you name your database tables and fields following CakePHP convention, it becomes trivial to set up relationships between them.

Virtual Fields

In addition to accessing the fields existing in the database, a Model can be used to create virtual fields for consistent formatting of data that you don't want to store redundantly in your database or have to recreate each time you want to use it.

Data Validation

Programming maxim #1: Never trust user input. Data validation in our Model allows us to ensure that the data entered matches what we are expecting and are capable of storing in our database fields.