I'm testing out somethings of Code Igniter and I noticed that code igniter doesn't provide a way to let the user set parameters in the constructor of a model.
Then I searched around a bit and I found out that someone actually find it useless to have constructor in models. Why is that?

I'd love to do things like:

$user = new User(123); // 123 = id
$user->getName();

or something like that with models. But now it turns out that we shouldn't use constructors for them.

1 Answer
1

I'm throwing that off my hat cause i don't know anything about Code Ignitor but i know why most models usually feature a constructor less pattern.

The reason is for serialization et deserialization. Many languages (Vb.net and C# for instance) don't allow serialization based on a constructor enabled class. Because, when deserializing a class that was serialized, it would have to go through the constructor which is impossible in deserialization process because it's not part of the usual code path.

My guess is that the same thing occurs with Code Ignitor, they decided to remove the constructor for similar purposes even though there is the magic wakeup in PHP.

I'm sorry, what do you mean by serialization? I've never heard anything about it.
–
JefffreyJan 10 '12 at 1:01

Serialization is the process of transforming an object or some less complex data such as an array into a string of characters or into a binary string that can be then deserialized back into the object/array or any other resource.
–
Mathieu DumoulinJan 10 '12 at 1:41

In PHP, you can only serialize PHP data, so objects, arrays and scalar data. Resources cannot be serialized as they are contextual to a specific extension.
–
Mathieu DumoulinJan 10 '12 at 1:42

What does it has to do with models? I still don't get it.
–
JefffreyJan 10 '12 at 2:36

Models represent raw data from a source not necessarily from databases, it can be from and XML file, a binary file (such as a jpeg or gif), a web service (Soap XML) or any other common formot. Therefore, you need a way to, most of the time, be able to serialize and deserialize the data from and to an object to/from another format. In the case of databases, we usually do it the crude way, select the data and copy the columns into the properties, but serialization and deserialization in the case of external files or sources is often used...
–
Mathieu DumoulinJan 10 '12 at 12:43