Which Code Should Go Where in MVC Structure - php

My problem is in somewhere between model and controller.Everything works perfect for me when I use MVC just for crud (create, read, update, delete).I have separate models for each database table .I access these models from controller , to crud them . For example , in contacts application,I have actions (create, read, update, delete) in controller(contact) to use model's (contact) methods (create, read, update, delete).
The problem starts when I try to do something more complicated. There are some complex processes which I do not know where should I put them.
For example , in registering user process. I can not just finish this process in user model because , I have to use other models too (sending mails , creating other records for user via other models) and do lots of complex validations via other models.
For example , in some complex searching processes , I have to access lots of models (articles, videos, images etc.)
Or, sometimes , I have to use apis to decide what I will do next or which database model I will use to record data
So where is the place to do this complicated processes. I do not want to do them in controllers , Because sometimes I should use these processes in other controllers too. And I do not want to put these process in models because , I use models as database access layers .May be I am wrong,I want to know . Thank you for your answer .

Just a short comment (no solution) AFAIK that is an eternal question - MVC is just a pattern, and as such, is in theory implementable cleanly. In practise, due to limitations set by available tools (such as programming language library contents and UI component interface design..) you have to make local decisions. The important thing is that you aim to separate these...and not have everything in one mess. I take my comment off the air and am left to see if someone has a "final solution".

For simple tasks I would write action helpers (e.g. sendNewsletter).
For sophistocated tasks I woud create services (eg. email, auth etc.).

In MVC, you should place those things in the model (for reuse reasons for one).
However, in HVMC, you could place them wherever (such as in a controller) and call the controllers from within your application.

I would make your controllers simple.
In many ways the model allows you to offload a lot of the complexity that would otherwise occlude your controller code. Its this division of complexity which will make your code more easily understood, and easier to maintain.
personally I try to keep my models resembling real world objects, not databases tables or rows. It makes it much easier if you have made things speak in more readable terms. A single real world object might involve 5 or 6 database tables... And it would be a rather large hassle to speak with 5 or 6 models, when all you want to do is turn on a switch, or pick a flower, or paint an icon, or send a message.

What's wrong with a controller using multiple models? Isn't the point of MVC to make the model reusable? In your first scenario, it's perfectly fine to send emails and manipulate other model objects from wherever the "register user" controller code is.
In regard to your second scenario, why can't SearchController use ArticleModel, ImageModel and VideoModel? It's fine to have a controller without a model. SearchController doesn't need a SearchModel class, it just uses the other model classes.
I'm trying not to get into a rant about MVC in web apps, but basically, IMHO the controller is just a high-level list of steps to complete an operation. As a rough example, the "register user" controller code should do each of the following steps in roughly one or two lines of code:
Validate the input
If not valid, redisplay the form with an error
Create the new UserModel object from the form input
Insert the new UserModel object into the database
Create/edit whatever other model objects are necessary
Send off an email to the new user
Display a "registration successful" page
How those steps are coded largely depends on whatever framework/architecture you're using.

Keep your controllers clean. For backend processing use Manager classes like MailManager etc..

Related

Advantages of Multiple Controllers over Single Controller in MVC?

I'm developing a laravel app and would like to know some best practices.
As an example, I'm thinking about creating multiple controllers instead of writing more than 10 methods in a single controller.
I would like to know what are or( if there are any ) advantages other than code readability.
My main concern is that how does it affect when there are more files to compile by the PHP compiler.
Since I'm using a framework is it going to compile all the files or only the file requested by web.php
Some insight would be great!
If the 10 methods you have in a controller are all related, then keep them in that controller. If you have a FruitController with methods related to performing actions on types of Fruit, but you also include some methods for performing actions on Vegetables, move the Vegetable methods to a new controller.
Consider encapsulation when composing your files.
In general, avoid making files for the sake of it. If it makes sense to create a new file as the logic you intend to place inside that file has no other existing home, then fine, otherwise add your logic to an existing file.
I'm not sure splitting related code into separate files increases readability, large files can be readable as long as the code is well formatted and consistent (amongst other things). Check out this book on clean code if you're interested.
What you will get though is a decrease in productivity and maintainability by having to flick through and maintain several files that are all related.
There is no advantage of using multiple controllers instead of one controller, as long as it is related to one single model. You may say it increases readability, but this is better to unify them in one single controller which is associated with your model and try to pick expressive names for the methods. The main idea is to create one single controller associated with each of your models. Feel free to add as much as methods possible into your models to talk to your database and make queries and call those methods in the associated controller. Then you can trigger those controllers through the web.php routes to handle your data and pass them to the view layer.
When you create separate controller for particular functionality this is more readable for old and new developer.
Also please check this link
From laravel:
Instead of defining all of your request handling logic as Closures in route files, you
may wish to organize this behavior using Controller classes. Controllers can group
related request handling logic into a single class. Controllers are stored in the
app/Http/Controllers directory.
I recommend that you divide your logic into different controllers. For example you can place all your user logic into one controller userController.php:
Create User
Edit User
Delete User
Then create another controller to manage the logic for another controller like sending emails etc. In this way your logic is more organized, easy to work with and you can find and update your methods easier.

Why separate Model and Controller in MVC?

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?
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.
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.

Mapping between Model, View and Controller in PHP MVC implementation

Overview: I am building a CMS using PHP, and I am trying to implement this using MVC. I am trying to extend my code using this structure, as it represents an accurate representation of MVC and it is quite straightforward. To communicate with my database I use Domain Objects and Data Mappers.
Questions:
Is it really necessary to have a 1:1:1 mapping between a model, a view, and a controller?
Example: For a blog system, when displaying a blog entry page I would create a controller called DisplayEntryController, and a View called DisplayEntryView. The view would get its information from the BlogMapper class (which communicates with the DB to retrieve the current blog entry) and a CommentMapper class (which communicates with the DB to retrieve the comments for the current blog entry). Is this good practice, considering that view works with 2 model objects? If not what is the alternative? If yes, how can this be implemented in a generic way?
Can multiple controllers handle one page? For the example above, would it be possible to have a DisplayEntryController and a CommentController handling the relevant parts of a page displaying the blog entry? If yes, how would the 2 controllers coordinate?
Thank you in advance. Examples will be greatly appreciated.
Most PHP MVC implementations I've seen on the web use the page approach to organise their MVC. E.g. for the Home page, you have one view, one controller and one model. Routing for 1:1:1 mapping in MVC is straightforward, as you can enforce the location and naming of your MVC components, and when a request for the Home page comes it automatically looks for the following classes: HomeView HomeController and HomeModel.
This obviously doesn't work well in larger projects. How should routing be handled to support routing to multiple models (DataMappers), multiple views, without creating an overcomplicated router or adding a complex dependency injection layer?
Example: As discussed above, when displaying a blog entry you display
the blog entry code and the comment section. To achieve this, it
communicates with two DataMappers, the one which gets the blog entry,
and the one which returns the comments for the blog. How can the view
be assigned to work with these two datamappers to get the data from
the DB?
There is no requirement to have a 1:1 mapping of the model, controller and view.
MVC works of a concept of a tiered approach to handling your application, with each tier being handled by 'agents' to implement the way they see fit. To explain this further, consider the following scenario.
Assume you process data, then hand them over to someone to store. You don't care where they store it and how they store the data, as long as the information is available again when you need it. You can happily go about processing your data, and then say to them for example 'This is project data for Client X, store it,' and later say 'Can you give me the project data for Client X.'
SO MVC works on this approach, whether the data storage guys dump all data together or pack them away is not important to you. However, what is important is the interface between the two parties when sending and retrieving. For example, you could decide to store the information as either Client data, or Project Data, or both.
Likewise, you could have agents collecting data and handling it to you to process. You don't care how many interfaces they use (for example, phone, web, email, mobile devices), but you care about what data they hand you. (Of course a rule might dictate that only web information must be handled). So the interfaces for collecting data might be different.
Therefore, each agent can use the most efficient method (and even combine or split them) to get the system working in their side, and therefore there is no mapping of the data.

CodeIgniter, multiple queries in same model method or multiple calls to model in controller?

I'm just starting to convert some basic applications to CodeIgniter and I'm trying to make sure that I start off on the right footing.
Most actions in my controller require at least 1 query and as I see it there are 2 ways to go about this...
Combine the queries into a single method in the model, therefore making only a single call to the model from the controller.
Have each query be its own method in the model, then call each method in turn from the controller.
So far I've adopted my own policy but I'm not sure if it's advised or breaking the MVC pattern.
If the queries are directly related to one another and only ever run together in sequence (the 2nd query is dependent on the 1st running successful), or data from the 1st query is passed to a 2nd query and it's the 2nd query that returns the actual display result set, then I go with #1
If each of the queries is returning its own individual result set for display, then I go with #2
Is there a recommended way to structure and separate the logic in this scenario?
The last thing I want to do is cause myself a nightmare later down the line. My gut instinct is telling me that as much of the logic should be in the controller as possible.
Your thinking is right in that if a certain set of queries will only ever be run together, they should belong to the same method in the model. Free-standing queries should be in methods of their own, this way you can call them from the controller when required.
To combine multiple queries, you can either make multiple calls from the controller like this:
$this->your_model->doQuery1();
$this->your_model->doQuery2();
$this->your_model->doQuery3();
Or (and this is what I would do), create a wrapper method in the model that runs those three queries.
So you can do
$this->your_model->runQueries();
where
function runQueries() {
$this->doQuery1();
$this->doQuery2();
$this->doQuery3();
}
This makes it more malleable to later change.
Finally, as for your statement 'as much of the logic should be in the controller as possible', this actually goes against the school of though of skinny controller, fat model that some people subscribe to. As any other school of thought, it is not set in stone.
First of all: slapping on a framework on exiting application - always a bad choice. Frameworks do not make you application better. They are there to make development faster.
Also, you have to understand that CodeIgniter is not really implementing proper MVC. Instead it is mimicking Rails architecture and naming conventions. It's actually closer to MVP pattern.
In any case, controllers must be as light as possible.
If implementing proper MVC or MVC-inspired pattern, all of the domain business logic would be in thee model layer and all of presentation logic in the views. Controller would be only passing relevant data to model layer and current view.
When writing code for CodeIgniter, you should keep as much domain logic as possible in the "models" and most of the presentation logic in the view helpers.
What in CodeIgniter are called "models" are mostly domain objects, which sometimes are merged with storage logic (violating SRP) to implement active record pattern.
The best option for you would be to create higher level "models" which would act as services and would separate the controllers from direct interaction with CodeIgniter's "models".
In your described situation, where you have to make two requests to different "models", this operation would be done is the such services. And the service aggregate the data from both "models" and pass it to the controller.
For example: if you are registering new user, you would have to perform two operations - create an entry for the account in storage (usually - database) and sent user notification to email. Those both operations can be contained in the service, that is responsible for user management.
Controller would only ask the service to crate new account. Fact that service would perform multiple operations( initialize a User "model", assign data to it, store it and then on success, initiate Mailer and send an email) is completely irrelevant to the controller. Controller would only want to know the list of errors (if the list was empty, everything was ok).
.. my two cents.

What would my controller be in these scenarios in a mvc web application?

1) Where does the homepage of your website fit into "controllers"? I've seen some people use a "page" controller to handle static pages like, about, home, contact, etc., but to me this doesn't seem like a good idea. Would creating a distinct controller just for your homepage be a better option? After all, it may need to access multiple models and doesn't really flow well with the whole, one controller per model theory that some people use.
2) If you need a dashboard for multiple types of users, would that be one dashboard controller that would have toggle code dependent upon which user, or would you have say a dashboard action within each controller per user? For example, admin/dashboard, account/dashboard, etc.
3) It seems to me that using the whole simple CRUD example works like a charm when trying to explain controllers, but that once you get past those simple functions, it breaks down and can cause your controllers to get unwieldy. Why do some people choose to create a login controller, when others make a login function in a user controller? One reason I think is that a lot of us come from a page approach background and it's hard to think of controllers as "objects" or "nouns" because pages don't always work that way. Case in point why on earth would you want to create a "pages" controller that would handle pages that really have nothing to do with each other just to have a "container" to fit actions into. Just doesn't seem right to me.
4) Should controllers have more to do with a use case than an "object" that actions can be performed on? For all intensive purposes, you could create a user controller that does every action in your whole app. Or you could create a controller per "area of concern" as some like to say. Or you could create one controller per view if you wanted. There is so much leeway that it makes it tough to figure out a consistent method to use.
Controllers shouldn't be this confusing probably, but for some reason they baffle the hell out of me. Any helpful comments would be greatly appreciated.
1) I use a simple homebrew set of classes for some of my MVC stuff, and it relates controller names to action and view names (it's a Front Controller style, similar to Zend). For a generic web site, let's assume it has a home page, privacy policy, contact page and an about page. I don't really want to make separate controllers for all these things, so I'll stick them inside my IndexController, with function names like actionIndex(), actionPrivacy(), actionContact(), and actionAbout().
To go along with that, inside my Views directory I have a directory of templates associated with each action. By default, any action automatically looks for an associated template, although you can specify one if you wish. So actionPrivacy() would look for a template file at index/privacy.php, actionContact() would look for index/contact.php, etc.
Of course, this relates to the URLs as well. So a url hit to http://www.example.com/index/about would run actionAbout(), which would load the About page template. Since the about page is completely static content, my actionAbout() does absolutely nothing, other than provide a public action for the Front Controller to see and run.
So to answer the core of your question, I do put multiple "pages" into a single controller, and it works fine for my purposes. One model per controller is a theory I don't think I'd try to follow when working with Web MVC, as it seems to fit an application with state much better.
2) For this, I would have multiple controllers. Following the same methods I use above, I would have /admin/dashboard and /account/dashboard as you suggest, although there's no reason they couldn't use the same (or portions of the same) templates.
I suppose if I had a gazillion different kinds of users, I'd make things more generic and only use one controller, and have a mod_rewrite rule to handle the loading. It would probably depend on how functionally complex the dashboard is, and what the account set up is like.
3) I find CRUD functionality difficult to implement directly into any layer of MVC and still have it be clean, flexible and efficient. I like to abstract CRUD functionality out into a service layer that any object may call upon, and have a base object class from which I can extend any objects needing CRUD.
I would suggest utilizing some of the PHP ORM frameworks out there for CRUD. They can do away with a lot of the hassle of getting a nice implementation.
In terms of login controller versus user controller, I suppose it depends on your application domain. With my style of programming, I would tend to think of "logging in" as a simple operation within the domain of a User model, and thusly have a single operation for it inside a user controller. To be more precise, I would have the UserController instantiate a user model and call a login routine on the model. I can't tell you that this is the proper way, because I couldn't say for sure what the proper way is supposed to be. It's a matter of context.
4) You're right about the leeway. You could easily create a controller that handled everything your app/site wanted to do. However, I think you'd agree that this would become a maintenance nightmare. I still get the jibbly-jibblies thinking about my last job at a market research company, where the internal PHP app was done by an overseas team with what I can only assume was little-to-no training. We're talking 10,000 line scripts that handled the whole site. It was impossible to maintain.
So, I'd suggest you break your app/site down into business domain areas, and create controllers based on that. Figure out the core concepts of your app and go from there.
Example
Let's say I had a web site about manatees, because obviously manatees rock. I'd want some normal site pages (about, contact, etc.), user account management, a forum, a picture gallery, and maybe a research document material area (with the latest science about manatees). Pretty simple, and a lot of it would be static, but you can start to see the breakdown.
IndexController - handles about page, privacy policy, generic static content.
UserController - handles account creation, logging in/out, preferences
PictureController - display pictures, handle uploads
ForumController - probably not much, I'd try to integrate an external forum, which would mean I wouldn't need much functionality here.
LibraryController - show lists of recent news and research
HugAManateeController - virtual manatee hugging in real-time over HTTP
That probably gives you at least a basic separation. If you find a controller becoming extremely large, it's probably time to break down the business domain into separate controllers.
It will be different for every project, so a little planning goes a long way towards what kind of architectural structure you'll have.
Web MVC can get very subjective, as it is quite different from a MVC model where your application has state. I try to keep major functionality out of Controllers when dealing with web apps. I like them to instantiate a few objects or models, run a couple of methods based on the action being taken, and collect some View data to pass off to the View once it's done. The simpler the better, and I put the core business logic into the models, which are supposed to be representative of the state of the application.
Hope that helps.

Categories