Chapter: Write your own business classes

−
Table of content

To be able to respect the layer model, it is recommanded to do all the business processing and the services in classes dedicated to it.

In this kind of classes, you will manipulate, for example, daos, data from daos or others, do all the processing other than display. The methods of your controllers will thus be lighter and the business processing will be reusable in other actions.

Business classes and services in Jelix are classic PHP classes which have nothing specific. The only thing that you have to respect is to specify it in a file named "name_of_class.class.php" in the classes directory of the module :

The difference between a service class and the other classes is that a service class gives a service. It doesn't need to be instanciated each time we use it because it doesn't have "discriminating" property. Only one instance is enough for all the application.

For example, a "factory" type class, which retrieves sets of data, is a service class. On the other hand, a class representing a product, which thus has identifying fields, is a non service class.

Jelix proposes the jClasses class, which avoids to do an include and instantiate yourself.

jClasses gives two static methods, to which you give a selector :

createInstance($ClassSelector); (or create($ClassSelector) )

getService($ClassSelector);

The first will, for each call, give a new instance. The second will allways give the same instance of the class. getService will thus be used for the service classes, and createInstance for the others.

If our StockService class is in the "shop" module, here is an example in an actiongroup :

This manual is distributed under the terms of licence Creative Commons by-nc-sa 3.0. Therefore you're allowed to copy, modify and distribute and transmit it publicly under the following conditions: Attribution, Noncommercial, Share Alike.