5

I'm trying to understand the MVC pattern in Phalcon.

In my current application I only need ONE template file for each table. The template contains the datagrid, the SQL statement for the SELECT, the form, add/edit/delete-buttons, a search box and all things necessary to interact with the database, like connection information (of course using includes as much as possible to prevent duplicate code). (I wrote my own complex framework, which converts xml-templates into a complete HTML-page, including all generated Javascript-code and CSS, without any PHP needed for the business logic. Instead of having specific PHP classes for each table in the database, I only use standard operation-scripts and database-classes that can do everything). I'm trying to comply more with web standards though, so I'm investigating alternatives.

I tried the INVO example of Phalcon and noticed that the Companies-page needs a Companies model, a CompaniesController, a CompaniesForm and 4 different views. To me, compared to my single file template now, having so many different files is too confusing.

I agree that separating the presentation from the business logic makes sense, but I can't really understand why the model and controller need to be in separate classes. This only seems to make things more complicated. And it seems many people already are having trouble deciding what should be in the model and what should be in the controller anyway. For example validation sometimes is put in the model if it requires business logic, but otherwise in the controller, which seems quite complex.

I work in a small team only, so 'separation of concerns' (apart from the presentation and business logic) is not really the most important thing for us.

  • If I decide not to use separate model and controller classes, what problems could I expect?
Dylan
  • 9,129
  • 20
  • 96
  • 153
  • If all you're designing is a basic CRUD system, with only one model to one controller, then you don't need that separation.... but for business systems, each controller might be accessing data from several different models, and a model might be referenced from several different controllers..... and then the separation is important – Mark Baker Dec 13 '15 at 23:37
  • 1
    Controller is an interrmediary between your models and a client. You separate controllers from a model layer because there might be different ways to request the same models: eg HTTP API, CLI, Some-other-crazy-api. In all these 3 cases you interact with the same models but through different APIs. Which means - the less knowledge API has about your model - the better. – zerkms Dec 13 '15 at 23:37

2 Answers2

5

Phalcon's Phalcon\Mvc\Model class, which your models are supposed to extend, is designed to provide an object-oriented way of interacting with the database. For example, if your table is Shopping_Cart then you'd name your class ShoppingCart. If your table has a column "id" then you'd define a property in your class public $id;.

Phalcon also gives you methods like initialize() and beforeValidationOnCreate(). I will admit these methods can be very confusing regarding how they work and when they're ran and why you'd ever want to call it in the first place.

The initialize() is quite self-explanatory and is called whenever your class is initiated. Here you can do things like setSource if your table is named differently than your class or call methods like belongsTo and hasMany to define its relationship with other tables.

Relationship are useful since it makes it easy to do something like search for a product in a user's cart, then using the id, you'd get a reference to the Accounts table and finally grab the username of the seller of the item in the buyer's cart.

I mean, sure, you could do separate queries for this kind of stuff, but if you define the table relationships in the very beginning, why not?

In terms of what's the point of defining a dedicated model for each table in the database, you can define your own custom methods for managing the model. For example you might want to define a public function updateItemsInCart($productId,$quantity) method in your ShoppingCart class. Then the idea is whenever you need to interact with the ShoppingCart, you simply call this method and let the Model worry about the business logic. This is instead of writing some complex update query which would also work.

Yes, you can put this kind of stuff in your controller. But there's also a DRY (Don't Repeat Yourself) principle. The purpose of MVC is separation of concerns. So why follow MVC in the first place if you don't want a dedicated Models section? Well, perhaps you don't need one. Not every application requires a model. For example this code doesn't use any: https://github.com/phalcon/blog

Personally, after using Phalcon's Model structure for a while, I've started disliking their 1-tier approach to Models. I prefer multi-tier models more in the direction of entities, services, and repositories. You can find such code over here: https://github.com/phalcon/mvc/tree/master/multiple-service-layer-model/apps/models But such can become overkill very quickly and hard to manage due to using too much abstraction. A solution somewhere between the two is usually feasible.

But honestly, there's nothing wrong with using Phalcon's built-in database adapter for your queries. If you come across a query very difficult to write, nobody said that every one of your models needs to extend Phalcon\Mvc\Model. It's still perfectly sound logic to write something like:

$pdo = \Phalcon\DI::getDefault()->getDb()->prepare($sql);
foreach($params as $key => &$val)
{
    $pdo->bindParam($key,$val);
}
$pdo->setFetchMode(PDO::FETCH_OBJ);
$pdo->execute();
$results=$pdo->fetchAll();

The models are very flexible, there's no "best" way to arrange them. The "whatever works" approach is fine. As well as the "I want my models to have a method for each operation I could possibly ever want".

I will admit that the invo and vokuro half-functional examples (built for demo purposes only) aren't so great for picking up good model designing habits. I'd advise finding a piece of software which is actually used in a serious manner, like the code for the forums: https://github.com/phalcon/forum/tree/master/app/models

Phalcon is still rather new of a framework to find good role models out there.


As you mention, regarding having all the models in one file, this is perfectly fine. Do note, as mentioned before, using setSource within initialize, you can name your classes differently than the table they're working on. You can also take advantage of namespaces and have the classes match the table names. You can take this a step further and create a single class for creating all your tables dynamically using setSource. That's assuming you want to use Phalcon's database adapter. There's nothing wrong with writing your own code on top of PDO or using another framework's database adapter out there.

As you say, separation of concerns isn't so important to you on a small team, so you can get away without a models directory. If it's any help, you could use something like what I wrote for your database adapter: http://pastie.org/10631358
then you'd toss that in your app/library directory. Load the component in your config like so:

$di->set('easySQL', function(){
    return new EasySQL();
});

Then in your Basemodel you'd put:

public function easyQuery($sql,$params=array())
{
    return $this->di->getEasySQL()->prepare($sql,$params)->execute()->fetchAll();
}

Finally, from a model, you can do something as simple as:

$this->easyQuery($sqlString,array(':id'=>$id));

Or define the function globally so your controllers can also use it, etc.


There's other ways to do it. Hopefully my "EasySQL" component brings you closer to your goal. Depending on your needs, maybe my "EasySQL" component is just the long way of writing:

$query = new \Phalcon\Mvc\Model\Query($sql, $di);
$matches=$query->execute($params);

If not, perhaps you're looking for something more in the direction of

$matches=MyModel::query()->where(...)->orderBy(...)->limit(...)->execute();

Which is perfectly fine.

Ultimater
  • 4,647
  • 2
  • 29
  • 43
1

Model, View and Controller were designed to separate each process.

Not just Phalcon uses this kind of approach, almost PHP Frameworks today uses that approach.

The Model should be the place where you're saving or updating things, it should not rely on other components but the database table itself (ONLY!), and you're just passing some boolean(if CRUD is done) or a database record query.

You could do that using your Controller, however if you'll be creating multiple controllers and you're doing the same process, it is much better to use 1 function from your model to call and to pass-in your data.

Also, Controllers supposed to be the script in the middle, it should be the one to dispatch every request, when saving records, when you need to use Model, if you need things to queue, you need to call some events, and lastly to respond using json response or showing your template adapter (volt).

We've shorten the word M-V-C, but in reality, we're processing these:

HTTP Request -> Services Loaded (including error handlers) -> The Router -> (Route Parser) -> (Dispatch to specified Controller) -> The Controller -> (Respond using JSON or Template Adapter | Call a Model | Call ACL | Call Event | Queue | API Request | etc....) -> end.

NosiaD
  • 587
  • 1
  • 6
  • 18