I've got a question regarding a conflict / conundrum I've run into with my application.
I want to make some common "stuff" available to all of my models and controllers, such as data from a cache, or session information, as well as the methods of my PDO wrapper.
Currently each individual feature controller and feature model extends a base controller and base model, which in turn extend a single object that does all of that common stuff.
A controller will get called by a router/dispatcher, and the controller will then call on a model to get some data. The problem with this is it means the main Object gets constructed twice: once when the feature controller is called, and again when the feature controller calls the feature model.
See the diagram below:
Obviously I'm doing something wrong, so I was wondering if there's some kind of best practice solution to this issue.
What I dont want is to have to pass the stuff the object loads, through the controller, to the model. That means any time I have to add a new common element to Object, I have to pass it through to the Model.
It's far simpler and easier for $this->cache or $this->db or $this->session to always be universally available in both controllers and models (as well as future helpers and misc classes).
How would I go about solving this issue?
Thanks :)
I think you are going in a wrong path about solving this issue.
If you are building an MVC application, you should separate concerns, thats why we use MVC. To separate Models, Controllers and Views.
You should define what do you need Model to do, what will Controller do, and use View only for presentation logic.
In proper MVC, Model is a layer that deals with business logic, database access, validation etc. So Model is not a one class. And you can use many models in one controller. And Controller is just... connection between Models and Views. Models should be fat, and Controllers should be light.
The way you are doing this is in my opinion wrong, since you can do the same stuff in both model and controller and that is not what MVC is for. Controller should not do any logic, thats why we use Models, controller only tells models what to do, and based on their reaction we tell other Models to do something else, or render View with success or error message or with posts from database etc.
The way you can do this is to once you have invoked appropriate controller, use it to get models you need. And again, model is composed of lots of classes, so your model folder can be fat. From Controller you should have only methods to access models so that models can do some actions, and report back to Controller what they did. And based on that returned value you do some more actions or call View to render.
So you should not have one object that can be extended by both models and controllers.
Your model folder can look like this:
Models
- Entities
- Forms
- Validators
- Services
...
And then you call any of them in your controller to do some action, and report back.
If you really need to have the same functionality in both controllers and models then this didnt answer your question, but I think its wrong to do it like you started.
Hope this helps you, interesting question Il try to help some more if I can.
I get a feeling, that the root of your problems is bad architecture.
The main thing you have to understand about MVC and MVC-inspired design patterns is that the pattern is made from two layers: presentation later and model layer. Those layers should not share common functionality. Controllers (as well as views and templates) are part of presentation layer.
When you have variables like $this->cache, $this->db or $this->session in the controller, it means that you have a severe leak of abstraction. These are storage structures, which should be hidden fairly deep in the model layer. If your controller is interaction with them directly, you do not have a controller.
Next problem is your base class (the one you call Object for some reason .. while objects kinda are instances of a class). It seems to be responsible for quite a lot, especially the instantiation of different abstraction for interaction with storage. If you controller needs a PDO instance (for some exceptionally bizarre reason), then it should be injected in the constructor. Same goes for cache and session management.
And then there is that small thing that model is not an object or a class. It is a layer. And just like presentation layer it is composed from different kinds of structures. Usually the recommendation is to have:
structures that deal with logical entities, which is usually what domain objects are for
one or more types of storage abstractions: data mapper, repository, unit of work, dao and/or some similar structures.
something, that controls the interaction between the above mentioned structures so that they do not leak in the presentation layer, commonly referred as services
And yes, you are correct assuming that using controller to pass along structures is a bad practice. It violates LoD. Instead you should be providing your controller with a factory, that instantiates your model layer structures and provides them with necessary dependencies .. this post might help.
my two cents on the subject .. for a more precise advice you would have to show some code
Related
How will you write your controller in MVC pattern without PHP frameworks?
This is the simplest version of my controller,
//Controller
class Controller
{
private $model;
public function __construct($model){
$this->model = $model;
}
public function clicked() {
$this->model->string = "Updated Data, thanks to MVC and PHP!";
}
}
As you can see that only model is passed into my controller as its dependency.
This is how I understand the controller in MVC pattern which can be referenced in these following articles,
https://r.je/views-are-not-templates.html
http://www.sitepoint.com/the-mvc-pattern-and-php-1/
PHP framework developers probably disagree with this, because as most frameworks seem to be MVC, but probably are Model 2.
In a Model 2 application, requests from the client browser are passed
to the controller. The controller performs any logic necessary to
obtain the correct content for display. It then places the content in
the request (commonly in the form of a JavaBean or POJO) and decides
which view it will pass the request to. The view then renders the
content passed by the controller.
So if we are going to put these frameworks aside, how do you do your controller then?
I've written a series of articles for writing MVC applications, inspired by one of the links you posted. Among those there is an article about Controllers:
Controllers are taking SRP seriously
Have a read at it first.
So if we are going to put these frameworks aside, how do you do your
controller then?
My controllers don't have a reference to the view. They only update the model as shown in your code sample, and I think that's the right way to do. Controllers shouldn't contain binding logic to the view. Instead, the view gets its data from the model (see The View gets its own data from the Model where I also explain the advantages of such a design).
Controllers can consume as many dependencies as they want (they might need more than just the model injected), but if you follow SRP closely, controllers won't need a lot of dependencies.
In most popular frameworks, you see a controller with a bunch of actions and binding logic for view rendering; I instead separate all these actions into separate controllers so that I have a 1:1 relationship between controller and view. This allows me to have controllers without binding logic to the view (see link above for detailed explanation on how I do that). My Controllers also follow SRP more closely this way.
When I said above, that the controller updates the model, beware that MVC Models are not just Domain Models. In addition to Domain Models, View Models store the state that the view needs for rendering, e.g.: the view allowing to update an entity like let's say a User, needs to know which user needs to be updated (again, read articles for more detailed explanations). My Controllers have thus in most cases at least two dependencies,
a domain model (most frequently an ORM instance) allowing me to update the datasource
a view model allowing me to update the application state (like which user is to be updated, search filters, ...) necessary for view rendering
I'd not seen Model 2 before this question, but as far as I can tell it is just a Java-specific approach to MVC, it isn't a separate design pattern as such.
You've not really explained why you think the PHP frameworks you mentioned aren't following MVC, in ZF at least it is quite common practice for dependencies to be passed in via. a controller's constructor as you have in the example from your own framework.
It's easy to fall down the rabbit hole with design patterns, really a lot of it is down to interpretation. Just because your implementation of a pattern isn't the same as another, doesn't necessarily mean the other implementation is wrong.
Shouldn't models just describe data that will be passed from a controller to a view? Doesn't that make models unnecessary in weakly typed languages? In PHP, they are doing DB work in models, but isn't that wrong? As I see it, models are just unnecessary in weakly typed languages...
There are some misconceptions about the term model. Microsoft's MVC3 framework has the concept of a view-model, which is simply the data you use to render your views. This isn't however what the M stands for exactly in MVC. The model includes your business entities. We have thin controllers and fat models, but very thin view models. Our controllers make calls to services that perform business logic, and the controllers never do this logic themselves. We then translate our business entities (our data models) and convert them into a lightweight view model, which can be used for rendering a view.
So to answer your question
Shouldn't model just describe data that will be passed from controller to view?
Then perhaps what you are really asking is aren't view-models unnecessary? I'm not sure why you think this. View model + view makes the result. In PHP it can be helpful to define a class with easily accessible properties on it. This is just sensible for clarifying your expectations and prevents you from calling methods with hideously long sets or arguments. In JavaScript there is no need to define a view model as such, you just push the properties onto a new object and pass it along with your view to your view rendering logic. This is more a reflection of the OO pattern these languages use and not the fact that they are weakly typed.
If you are asking if model is unnecessary, then you have missed the purpose of the MVC architecture. A big part of MVC is that you separate your concerns. Why apply any architecture to your code? I am sure you can find a better explanation of the motivation behind MVC than I can give you.
A model is a useful conceptual tool, even if it's not strictly necessary in PHP to separate it from the DB code e.g. you can have a data object associated with each table that encapsulates some business logic, or define a set of business entities that aggregate the data across tables into domain-specific objects that the controllers can then use, or just have one monster DB object that has all the access functions and returns the entities. This has definite advantages over having DB code directly in use by the controllers:
If you are defining complex data structures that run across DB tables, you don't want to do that in controller code due to the risk of duplication - far better to have a single definition that enforces consistency across the system. Although this can introduce dependencies, having one function/object that defines that data makes it easy to find out where the data is used so you can fix things.
Third party maintenance is far easier if there's one place to go to where all the data structure definitions are found.
It makes unit testing easier if you can swap out the whole model or parts of it and replace it with mock object(s) that will provide test data
It makes controllers lighter and therefore more readable and maintainable
So you could argue that it's not necessary, but it helps a lot.
I've always seen models as a tool to provide data. That means that your controller doesn't ever have to worry about the data source, and if you want to switch from using a database to XML files then you only have to swap out your model.
So long as you have some data provider abstraction. Some Models will do low level validation (tightly coupled to the storage engine - null checks etc) but the controller "should" do all of the business logic/validation.
I personally have a thin struct like class that is mapped to each table (all implementing IDataStruct). This struct, or a collection thereof, is the only thing that moves between the DomainObject and the DataProvider. I can then enforce via my interface what datastruct I should be receiving. This is not a silver bullet but I have found it to work well (Makes things like caching and unit testing quite easy)
I hope this hasn't confused the issue.
Ok, it's my fault. I've never ever learned programming at a school and that's why i'm always ending up in a spaghetti code. I've always curious about different patterns and tried to understand them at least in a basic level.
MVC is my worst fear and i think i'll be never able to use it's advantages because of i don't understand it's fundamentals.
My actual question/problem looks like:
The front controller calls a 'Core' class which is doing some initialization then it calls the actual controller with the correct action/parameters. The controllers always extending the 'Core' class so i can acces it's variables, etc. They're working nicely together but here comes my real problem.
Some kind of methods (getting a database entry in most of the cases) are required in different cases. (e.g. a product needs it's manufacturer)
In this scenario i have two (bad) choices:
Inject the required method into the 'Core' class so it's getting bloated over time
Inject the required method into the actually called controller so i will end up a redundant codebase
I see a lot of possible problems in my approach:
Controllers are always extending 'Core' class
'Core' controller holds the database object so without it i cannot access my Db
Database functions (e.g. getting a product) are in the controllers but i cannot access them because they're always calling 'Core' first (extending problem again)
Please tell me:
Where is the biggest problem in my approach and where can i correct it?
Note:
Please don't treat this as a general question, i think this is an answerable thing. If you need some clarification, please ask for it and i'll try to lighten up things.
Thanks for your precious time, fabrik
Your data is represented to your Controller and View through the Model. The Model may be supported by a Repository but depending on the overhead you might want to provide your database access in your Model. The data architecture should be similar to this:
(Repository<===>)Model<===>Controller--->View
Your biggest problem is having the "Core" class, get rid of it asap.
By the way, the FrontController is not the only way to do things MVC things either.
Your second problem is that controller deals with database, it shouldn't. I suggest you use some abstract data layer, which you use only in your models. And controller should deal only with models, it shouldn't care how models get their data persisted and fetched.
Look into using a DI framework to automatically inject an instance of a repository into your controllers (or even better, a proxy class). Try to keep business logic outside of your controllers, but rather, refector it out into a helper or proxy class.
I tend to split my logic up into views => controllers (just for interaction between business later and view) => business logic => models (DTOs) => low-level data access at a minimum.
Also, if you need common helper functionality in your views, perhaps create several extensions to help.
My experience is mostly limited to PHP, yet as far as I know both Rails and ASP.NET MVC have taken the same path.
The point is that nearly every web framework I've ever come across implements controller actions as methods, e.g. create, edit, show, etc. These methods reside in a single class like PostsController, but they hardly ever share state or dependencies, because only one of them gets called during the whole request.
That's why to me this approach seems quite unreasonable, as the class only acts as some kind of namespace. Seeing examples with large chunks of barely related controller action code composing even larger controller classes doesn't help either. Yet a lot of frameworks do exactly that, and only a few use a class for each action.
So the question is, why is it so? Perhaps it's subjective, but I believe that I may have missed an important advantage of this approach.
I would argue that the MVC design pattern in general dictates this approach to building controllers. The main purpose of the controller is to provide the appropriate "wiring" between the associated view and the models it needs to interact with, along with any business logic needed to handle the input from the view. Controllers should just be a thin layer between these other components.
For example, Wikipedia describes the controller as follows:
The controller receives input and
initiates a response by making calls
on model objects. A controller accepts
input from the user and instructs the
model and viewport to perform actions
based on that input.
I do agree that controllers in other, non-web environments do maintain state, but the reason for the lack of state in PHP, for example, is simply that HTTP is a stateless protocol. Using MVC in this environment is inherently going to result in controllers that don't maintain state.
Why do so many MVC web frameworks favor grouping multiple controller actions in a single class?
That is essential to object oriented programming resulting in a properly layered software architecture where the controller objects encapsulate all responsibilities about domain objects (model). If there is a PostModel, then there should be a PostController responsible for calling the right business methods on the domain api to satisfy the user request and to push the results into the view. Having a controller class for every single possible request leads to a procedural structured architecture in my opinion.
On the other hand, if you have too many resonsibilities in your controller class, you should split these responsibilities into multiple controllers. It depends on your application at hand, there is no one-fits-all solution. Every controller should be responsible for a cohesive group of actions on the domain layer.
My understanding of the MVC is as follows (incase it's horribly wrong, I am afterall new to it)
Models are the things that interface with the database
Views are the design/layout of the page
Controllers are where everything starts and are essentially the page logic
I'm using CodeIgniter but I would hazard a guess it's not just limited to that or possibly even just to PHP frameworks.
Where do I put global classes?
I may have a model for Products and I then run a query that collects 20 products from the database. Do I now make 20 models or should I have a separate class for it, if the latter, where do I put this class (other controllers will need to use it too)
Model is the wrong word to use when discussing what to do with products: each product is a value object (VO) (or data transfer objet/DTO, whatever fits in your mouth better). Value objects generally have the same fields that a table contains. In your case ProductVO should have the fields that are in Products table.
Model is a Data Access Object (DAO) that has methods like
findByPk --> returns a single value object
findAll --> returns a collection of value objects (0-n)
etc.
In your case you would have a ProductDAO that has something like the above methods. This ProductDAO would then return ProductVO's and collections of them.
Data Access Objects can also return Business Objects (BO) which may contain multiple VO's and additional methods that are business case specific.
Addendum:
In your controller you call a ProductDAO to find the products you want.
The returned ProductVO(s) are then passed to the view (as request attributes in Java). The view then loops through/displays the data from the productVO's.
Model is part of your application where business logic happens. Model represents real life relations and dependencies between objects, like: Employee reports to a Manager, Manager supervises many Employees, Manager can assign Task to Employee, Task sends out notification when overdue. Model CAN and most often DO interface with database, but this is not a requirement.
View is basically everything that can be displayed or help in displaying. View contains templates, template objects, handles template composition and nesting, wraps with headers and footers, and produces output in one of well known formats (X/HTML, but also XML, RSS/Atom, CSV).
Controller is a translation layer that translates user actions to model operations. In other words, it tells model what to do and returns a response. Controller methods should be as small as possible and all business processing should be done in Model, and view logic processing should take place in View.
Now, back to your question. It really depends if you need separate class for each product. In most cases, one class will suffice and 20 instances of it should be created. As products represent business logic it should belong to Model part of your application.
In CakePHP there are 3 more "parts" :
Behaviors
Components
Helpers
Logic that are used by many models should be made as a behavior. I do not know if CodeIgniter have this logic or not, but if it doesnt, I would try to implement it as such. You can read about behaviors here.
(Components helps controller share logic and helpers help views in the same way).
The simplest way is to:
Have a model class per database table. In this case it would be an object that held all the Product details.
Put these classes into a package/namespace, e.g., com.company.model (Java / C#)
Put the DAO classes into a package like com.company.model.dao
Your view will consume data from the session/request/controller In this case I would have a List<Product>.
Oh, you're using PHP. Dunno how that changes things, but I imagine it has a Collections framework like any modern language.
#Alexander mentions CakePHPs Behaviors, Components and Helpers. These are excellent for abstracting out common functionality. I find the Behaviors particularly useful as of course the bulk of the business logic is carried in the models. I am currently working on a project where we have behaviors like:
Lockable
Publishable
Tagable
Rateable
Commentable
etc.
For code that transcends even the MVC framework i.e. code libraries that you use for various things that are not tied in to the particular framework you are using - in our case things like video encoding classes etc. CakePHP has the vendors folder.
Anything that effectively has nothing to do with CakePHP goes in there.
I suspect CodeIgniter doesn't have quite as flexible a structure, it's smaller and lighter than CakePHP, but a quick look at the CakePHP Manual to see how Behaviors, Components, Helpers, and the Vendors folder may be helpful.
It should be an easy matter to just include some common helper classes from your models keep nice and DRY