Blueprint PHP Framework Tutorial – Part 5 (Models)

MVC modelFrom the last tutorial, we saw how controllers were structured. However we only passed a very simple ‘Hello world’ string to the view and didn’t make use of a model. Models are where the business logic of the application take place. The business logic can be anything from querying a database to making calls to an external API etc. The data returned from a model is passed back to the controller and the controller passes it to the view to format before sending it to the template. Simples…

The Blueprint PHP Framework is bundled with some sample models to show you how they work. We’ll create our own for our Frontend namespace in /app/Frontend/Model/Index.php (plus the changes we need to make to the controller). As with the controller in the previous tutorial, we need to set the namespace, and tell the script where the base model class is to extend it:

This is a shortened version of the model found in the Sample namespace. You can see the full version here. Like the controller class, the model has a setContainer method. This gets called form the controller where it passes the dependencies to the model. The model uses this method to extract the database object as a property of the model. The getRow() method simply takes an id and queries the database object which abstracts the SQL call the database itself. We’ll go over the database class in detail in a tutorial in the near future.

Quickly switching to your Index controller, we need to add a couple of things. We need to reference the model:

We also need to instantiate the model in the constructor:

Finally we need to update our indexAction() method:

Now, if you have setup the framework on your own machine and everything is correctly configured you should be able to load the information associated with id=1 in the ‘table1′ table. Models shouldn’t really be used to format the output (as it does with the implode function) but we’ll handle the formatting next time when we go over View in more detail.

2 thoughts on “Blueprint PHP Framework Tutorial – Part 5 (Models)

Leave a Reply