Multiple controllers or single master controller - php

Problem
I know this is a bit of a conceptual question, but I am designing a
system and I am not sure if I want to use one script as a "Master
Controller", that talks to my PHP classes for the business logic, OR
if I wanted to create multiple smaller controllers that only focus on
certain tasks.
Example
For example, if I wanted to control ALL the functions of the
site(user management, times heets, reporting, and so forth), should I
combine all those "getter/setter" functions into one script, or should
I break it up into sections (one controller for user management, one
for time sheets and so forth). I am using AJAX to call these scripts
when needed.
My Request
My thinking is that I should use multiple smaller controllers, that
way when multiple users are accessing the site, they are not all
trying to execute that same script at the same time. I would expect
that if I used one big controller, that it could cause problems with
symptoms that would act like a DDOS. However, I am unsure if that
would actually happen and wanted to get some opinions/alternatives
suggestions.
BTW, this is not a MVC architecture per-say, more of a custom monster I am creating.
Any insight would be greatly appreciated.

For a complex system with multiple Ajax calls, you might want to look at the Flux and React systems developed by Facebook. These are open source and available on GitHub. Facebook developed Flux because they got into difficulties with a complex MVC system.

The Single Responibility Principle suggests to split you controller. It's a fundamental principle of good object oriented design.

Related

MVC in PHP – General understanding and specific questions

I am currently trying to understand how the MVC framework does work in PHP. Therefore, I have created this basic sketch of how I think that MVC is implemented in PHP:
[I know that some steps are missing, e.g. how the Routerparses the route in order to know what View and Controller to load, but these steps are rather technical based and are not important in order to understand the general flow of MVC in PHP.]
I draw my understanding of MVC in PHP from this article series. However, I think that this structure will differ from most of the structures people think off, when they talk about MVC in PHP, because of this article (The article basically states that not only the Controller but also the View does communicate with the Model).
What I'd like to ask you now are several questions:
Is this generally a right way of implementing MVC in PHP?
How can I add a Login/Logout-System to this approach? So that user, who are not logged in, will always see the LoginView and users who are logged in can see different views? (I know how a login system does work, but I can't figure out where to place it in the MVC, so I don't have to insert the code multiple times, e.g. in each Controller.)
What if my application consist of multiple elements (say a user bar [with user name, link to settings, etc.], a navigation and a content container) that are always loaded? How can I assemble these elements to a final view? (The only idea that comes to my mind is to assemble the final view in each view separately, but that would mean that I have to insert the code for it multiple times in each view, which misses the point of MVC, doesn't it?)
What if I want to use AJAX in my application? My idea would be to send ajax requests through the framework as well, while only accessing controllers and views that are made for ajax? In other words the AjaxViews do only return e.g. json objects and the AjaxControllers do always expect authentication codes to prove that these ajax calls are legtitim?
I know that there have already been asked dozens of questions about MVC in PHP and I've been reading quiet a lot of articles until now, but I think that only reading does not enable me to understand MVC completely.
Furthermore, after reading the articles linked above, I'm not longer sure whether other articles about MVC, I find on the web, does explain MVC the same way as the articles above. Because if they don't, I'm trying to understand one framework while reading about two or multiple different approaches.
Thank you very much in advance for taking the time to answer my question!
-- --- --- Update --- --- --
According to the answer below I've changed my MVC sketch. Just in case someone finds this link and wants to know more.
Let me first answer your questions, then place my take on it.
There's no right way of writing MVC. There are so many flavors and variations, and that get even multiplied when talking about web MVC.
About Logging in and Logging out. I think the most robust system would be a Role Based Access Control combined with an Access Control List, see How can I implement an Access Control List in my Web MVC application?.
There are generally two approaches, either you have a 1:1 ratio between Controllers and Views, and then after the Controller is done, your bootstrap script calls the View with the same name (LoginController, LoginView), or your Controller returns the View name along with action and parameters, to be called by the bootstrapper. The view then picks a template, and that template can include other sub-templates (like the user bar, or the footer).
In that case, your view needs to have an ability to select a different template based on the Accept: HTTP header (and send something like Accept: application/json in your AJAX requests). Your view then returns a JSON template instead of an HTML template.
What is wrong with your sketch?
Your model isn't just the gateway to your database, it's where all the logic happens. All the computation. See this yet another excellent answer that explains How should a model be structured in MVC?.
The idea of MVC is to simply separate your application into three layers: Input (controller), Logic (model) and Output (view). This is to extend on the usual way PHP works (here's a request, give me a response, all in the same page).
For that reason, implementation details may vary, the concept is what matters. "Web MVC" is merely the result of good OOP practices and some naming convention someone made up a few decades ago.
It is for parallel development and code reuse ability. There is a separation of concern how your system works and how users work. This provides a solution of the problem. There is boundry now, MVC.

Organizing and building properly mid-size PHP projects

I wrote in PHP a learning management system for a small private school. It started a while ago when a lot of programming stuff was new to me. It is mostly scripts and includes based and doesn't contain classes or any MVC style organization, but it has grown big. What I am trying to do is to organize the current code without rewriting, so that it is good for fast iterations.
So far I changed it so that every role has its own folder/index/actions and all of them use one shared lib.php file to do sql queries and other related actions.
I talked to couple of MVC folks and considered PHPCake and Tonic as an option, but those seem to change dramatically what I already have. I am not sure if it just in my practice, but I just don't see how MVC will make it easier for me to develop faster. Can someone give tips or experience advise/opinions or maybe some helpful links. Thanks.
MVC can be a useful framework for developing applications into logically separated components in a somewhat 'natural' way. It can increase your ability to develop quickly based mainly off the fact that some portions of the framework will end up being reusable and allow you to leverage that fact to develop new views and similar quickly. However, it is not necessary to use any particular framework or scheme to develop quickly as it can be done with a properly designed application of any nature.
An important thing to consider when developing an application in such a manner is code reuse. For example, making it simple to display pages with common layouts through a centralized mechanism, or having user-related functions placed into a user class/function set which can be reused site-wide instead of having individual functionality to handle it on each page.
In terms of modifying an existing application, I would focus on trying to centralize the components you are able to and making use of those components henceforth. This also makes modifying routines simpler because instead of potentially changing functionality on many areas of the codebase, you can change it in a single location and effect the application as a whole.
Trying to make a pattern fit a problem is a very silly approach. Patterns are what code is not what what the code should be. In any object-oriented project presenting a user interface there will be instances of models, views and controllers - but there will also be lots of other patterns in the code - observers, decorators, iterators and more. They are useful learning constructs (e.g. "Here's how to implement a factory to build objects from relational data") and (human) language constructs (e.g. "That database connection class should be implemented as a singleton"). They are not design constructs.
so that every role has its own folder/index/actions
Unless you've got a rather unusual definition of 'role', this architecture makes no sense. The most common criteria for dividing up high-level functionality are separation of concerns and grouping around common data sources.
You've mentioned frameworks - trying to adapt existing code to fit into a framework is usually a bad idea - it won't fit. They can be of benefit in structure your application and reducing the amount of effort if you sse them from the start of the project. Not from the middle / end.
Put the new code you write under test. As the old code isn't, put it under test part-by-part as well. At the moment you've put everything under test, you should be fine for faster iterations.

Mix Javascript and PHP in my design model

I'm developing a web application and I'm using PHP and Javascript. Today, I'm starting to draw all the design class diagrams, but I don't know exactly how to mix both technologies.
I think that something like the following should be good:
But, really, I'm not sure if typing the .php extension in the class name is sufficiently clear, or what I need is to separate diagrams in two: one for Javascript classes and another one for PHP classes.
I'm using CodeIgniter (MVC pattern) and Javascript. Any suggestion will be really appreciated.
Thanks!
Usually, you don't want to do this. It's a problem of latency when viewing the web page in a browser. Each separate javascript file defeats caching and requires additional transfer time before a page can load. It's commonly advised to combine JS files wherever possible and practical to better take advantage of browser caching. So my first suggestion is to not arbitrarily split up your JS for architectural reasons...
Now, with that said, to answer you question in entirety, I think it depends on how you view JS. If you're looking at it form the perspective that it enhances your PHP application, then dividing it up along side your views is not bad (the above suggestion not withstanding).
However, I usually see JS as a separate application layer on top of the PHP application. The JS interacts with the PHP layer through defined APIs. So it's basically just a full blown GUI application that just so happens to use the API defined by the PHP application. So with that in mind, I usually build the JS application with its own architecture that's more dependent on itself then the PHP application. So in other words, just because a piece of the JS application interacts with PHP doesn't mean that the piece of code belongs with the PHP application.
Does that make sense?
Trying to put all your classes (even within one application - you have two: a PHP applicatoin and a JS application) on one UML diagram is pretty much a way to waste a lot of time and gain nothing.
Use UML to show dependecies within a package or a group of classes working together, but don't try to do it for a whole app.
I don't know the way you do things usually but in my projects, I tend to separate PHP and JS. First of all, its easier to develop and debug if you go that way, secondly, if you treat javascript as a second layer instead of being on the same level of programming as PHP you will get a working fallback in the case that your JS doesn't work, or the user of your web app have javascript disabled.
I tend to make everything work in PHP and later on I override some actions with javascript to get them working through ajax instead of the traditionnal way of working in old school Web.
--- Revision following first comment ---
Then, you might want to treat the PHP and the Javascript part as separates applications. The first system (PHP) generate the initial state. Upon user action the second system (JS) makes a query to the first one and wait for the answer, this way, you will setup some sort of API that will standardise your transactions.
I used to work with design information specialists and they often refer to Jesse James Garrett as a "Guru" in that field of expertise, you might want to check his site (there are premade stencils for omnigraffle, visio and few others).
Through his writing and example you might be able to find the right symbols and elements to represent your system.
Jesse James Garrett's website

PHP: Separating Business logic and Presentational logic, is it worth it? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Why should I use templating system in PHP?
I was just curious as to how many developers actually do this?
Up to this time I haven't and I was just curious to whether it really helps make things look cleaner and easier to follow. I've heard using template engines like Smarty help out, but I've also heard the opposite. That they just create unnecessary overhead and it's essentially like learning a new language.
Does anyone here have experience with templates? What are your feelings on them? Are the helpful on big projects or just a waste of time?
On a side note: The company I work for doesn't have a designer, there are just two developers working on this project charged with the re-design/upgrade. I also use a bit of AJAX, would this have issues with a template engine?
Not only does this practice make the code look cleaner, it also has many long term and short term benefits.
You can never go wrong with organizing code. First off it makes it much easier to maintain and easier to read if someone else has to pick up after you. I have worked with Smarty before and it is nice, it keeps the designers work from interfering with the program code.
Using template systems and frameworks would make it much easier to accomplish tasks. There is a rule of thumb you can follow which is DRY (Don't Repeat Yourself). Frameworks help you achieve this goal.
You may want to look into MVC, this is the model that these frameworks are based off of. But you could implement this design structure without necessarily using framework. Avoiding the learning curve. For frameworks like Zend, the learning curve is much greater than some other ones.
I have found that Code Igniter is fairly easy to use and they have some VERY helpful video tutorials on their website.
Best of Luck!!
Actually it's the business logic that needs to be separated from the views. You can use php as a "template language" inside the views.
You can use ajax on any template engine i think.
Edit
My original response addressed the question whether to use a template engine or not to generate your html.
I argued that php is good enough for template tasks, as long as you separate business logic from presentation logic.
It's worth doing this even for simple pages, because it enables you to:
isolate the code that is the brain of your application from the code that is the face, and so you can change the face, without messing with the brain, or you can enhance the brain without braking the looks
isolate 80% of bugs in 20% of your code
create reusable components: you could assign different presentation code to the same business code, and vice versa;
separate concerns of the feature requests (business code) from the concerns of the design requests (presentation code), which also usually are related to different people on the client side, and different people on the contractor side
use different people to write the business code and the presentation code; you can have the designer to handle directly the presentation code, with minimal php knoledge;
A simple solution, which mimics MVC and doesn't use objects could be:
use a single controller php file, which receives all requests via a .httpdaccess file;
the controller decides what business and presentation code to use, depending on the request
the controller then uses an include statement to include the business php file
the business code does it's magic, and then includes the presentation php file
PHP is a template engine (or if you prefer, a hypertext preprocessor). When HTML is mixed heavily with PHP logic, it does become very difficult to maintain, which is why you would have functions defined separately to build various parts and simply build the page from short function calls embedded in the HTML. Done like this, I don't see much of a difference between Smarty and raw PHP, other than the choice of delimiters.
Separation of concerns is a very important tenant to any type of software development, even on the web. Too many times I have found that people just throw everything into as few files as possible and call it a day. This is most certainly the wrong way to do it. As has been mentioned, it will help with maintainability of the code for others, but more than that, it helps you be able to read the code. When everything is separated out, you can think about easily.
Code Ignitor, I have found, has been the easiest to learn framework for working with PHP. I pretty much started my current job and was up and running with it within a few days, from never having heard of it, to using it pretty efficiently. I don't see it as another language at all, either. Basically, using the framework forces me to organize things in a manageable way, and the added functionality is anlagous to using plugins and such for jQuery, or importing packages in Java. The thought that it's like learning another language seems almost silly.
So, in short, organize organize organize. Keep in mind, though, that there is a level of abstraction that just becomes absurd. A rule of thumb is that a class (or file in our case) should do one thing very well. This doesn't mean it is a class that wraps around print, but takes a string, formats it using a complex algorithm and then prints it (this is just an example). Each class should do something specific, and you can do that without any framework. What makes MVC great, though, is that it lets you organize things further, not just on the single class level, but on the level of "packages", being Model, View, and Controller (at least in the case of these frameworks; there are other ways to package projects). So, now you have single classes that do things well, and then you have them grouped with similar classes that do other things well. This way, everything is kept very clean an manageable.
The last level to think about once you have things organized into classes, and then packages, is how these classes get accessed between packages. When using MVC, the access usually will go Model<->Controller<->View, thus separating the model (which is usually database stuff and "business" code in the PHP world), from the view (which usually takes information from the user, and passes it along to the controller, who will then get more information from the model, if necessary, or do something else with the input information). The controller kind of works like the switchboard between the two other packages usually. Again, there are other ways to go with packaging and such, but this is a common way.
I hope that helps.
Smarty and other php template frameworks really do nothing more than compile to PHP anyway, and they also cache their results in most cases to allow for faster processing. You can do this all on your own, but if you ever look at the compiled templates that Smarty generates, and compare to the original Smarty template you create, you can see that one is far more readable than the other.
I write mostly mod_perl these days and started using templates (HTML::Template) halfway through our ongoing project. If I had to make the decision again, I would use templates right from the start - rewriting later to use templates is kind of tedious, though rewarding because you get nicer and cleaner code. For anything bigger than 2-3 pages in php, I would also use some template engine.
One big advantage of a templating engine such as Smarty is that non-developers can use it to embed the necessary logic that is used on the front-end (one really can't separate logic and display on all but the simplest sites). However, if the developer is the one maintaining the pages then using PHP would be preferable in my opinion.
If you separate out large logic blocks and maintain a consistent patten for looping and for-each flow control statements (i.e. don't use print statements, or only use print statements for one-liners, etc.) Then that should be okay.

MVC as best practice for professional level programming?

Long time lurker, first time poster...
I'm now at the point where I'd almost call myself a professional grade PHP programmer and have a lot of code I re-use in various projects. Also, a lot of Open Source packages I've worked with use the MVC model and as a result I've done a lot of research recently into how it all works so I can better edit them as required.
At this point, I'm considering taking a bare-bones MVC framework (from a tutorial) and extending it as required for my forthcoming programming jobs.
My question is whether the MVC model with pretty much all application logic separated from the presentation layer is considered best practice over a well structured OOP website with coding on the page as necessary e.g setting function variables.
Or will I run into issues when I want coding flexibility e.g.
using something like PHPthumb for a gallery where I want different output
sizes on different pages and currently set parameters in the head
of the page
a contact form with x fields and a feedback form with y fields - will this require 2 differrent models rather than a generic form class again with some parameters set in the head of the page
some pages requiring ob_start() and ob_flush() but not others?
Please don't tell me not to build my own framework - I'd rather know how each little bit works than use a slab of code I know nothing about - I'm really interested in the opinion of people who have gone this route and build sites every day. What are the real pros and cons of this over plain (but well structured) OOP and bunch of pages to a site as opposed to 1 index.php page and separate files.
Cheers,
Niggles
I know you say you don't want this advice, but don't write your own. The first thing I've done at every single job I've ever worked at is picked up some existing code or framework, often commercial but highly modified, and begun maintaining it. You'll seldom get the option to write your own, and doing so is a bad idea. It's hard, expensive, and somebody else has already written a better MVC PHP framework than you're likely to write.
There are literally dozes of mature PHP frameworks, most of which have been around for over a decade. Choose one of them. It doesn't matter which one - they're all maintained by a dozen people at least as smart as you who've been writing MVC frameworks a lot longer, and have spent months or years refining their frameworks and listening to user input.
All that said, if you want to write your own on your own time, as a hobby, so you're not wasting your boss's money, then by all means. There's a huge variety of interpretations of MVC. Some frameworks view views as basically templates. I personally think you can throw as much raw PHP in there as you'd like, so long as it's purpose is display, and you do the usual smart things like distilling out shared code into functions. Some frameworks have virtually no business logic in the models (where it belongs IMO) but have very heavy controllers. The best thing you can do is try other frameworks and see how they work, and which you like best, and decide what you'd like to see changed. Then, set out to change it in your own.
You say you're almost ready to consider yourself a professional? The hardest lesson I had to learn was that professionals don't write their own low-level libraries. They don't reinvent the wheel on the company buck. They use off-the-shelf components and get the job done today, rather than a month from now. You don't want to use a slab of unfamiliar code? That's the biggest part of your life to come as a programmer - get used to it.
Writing your own framework is great for your own edification and for truly understanding the language.
Personally I find its as time consuming using a third party framework as it is to write your own. Yet I have total control of my own code, not something you can claim with any third party framework.
I also think many MVC frameworks are very resource intensive. For high volume sites you need to be prepared to throw hardware at them to get them to run nicely. For low volume sites (the majority) the rapid development of a third party MVC framework is a huge bonus.
So in my opinion if you have the time, roll your own and be proud of it. Just make sure you learn from others especially where security is concerned.
It all depends on what are you project requirements are and how you design your application objects. MVC do not force you to use an specific class or view design, It will only provide you with an architecture that will help you isolate the business logic from the presentation and the data layer making you application more scalable and easy to test.
In MVC you are not tied to one view per controller you can use as many views as you want per controller since every exposed method can call a view itself and control how it looks and behave based on the business logic you define. That said you can have 2 methods to return a full size image and a thumbnail without having to create two pages. You can set everything on the view from the controller, header meta-data, scripts, links, theme, content, etc...
In regard to the models, it again depends on your project requirements but definitely, in any case, if you have several pages with different purposes and they require to modify different data sources there should be a model for each one of them and what you can do after is to create a class that encapsulates the form functionality by calling the model for getting the fields to create form, get and save the data. This is just an idea you can do it in a lot of different ways, that is the beauty of OOP.
In the end it is not a matter of comparing a well structured OOP site against an OOP MVC site, It is more an analysis of the time and effort you spend working on building a site architecture that can succeed in isolating concerns at the same time it still readable and scalable while it meets your project requirements.
If you want to get more ideas about design patterns you can use google MVP design pattern and/or MVVM design pattern.
I have written my own framework. It does not take time to create the architecture and raw code. It's great if someone writes there own framework. But If documentation is not proper than definitely pain in asses. Completely depends upon yourself. I have written mine as well. It took almost 7 days to make framework QA ready :). but the main issue is to get satisfied by the piece of code you write in your framework. You would always like to improvise your framework and wanted it to be best ever. BLAH! BLAH! If you wish to write your own and you are confident enough for sustenance. GO for it.
Any MVC -- homegrown or not -- will allow you flexibility and re-usable code.
ob_start() / ob_* calls are no problem, they go in your model and called from your template, e.g.:
Hello <?php echo $this->getFormattedName(); ?>
where your model is
function getFormattedName() {
ob_start();
echo '' . $this->getName() . '';
$return = ob_end_clean();
return $return;
}
For your form scenario, you would probably want an abstract form class that defines how a field is made and its validation, then each specific form would extend your abstract.
You may want to consider using something like Zend Framework -- while it's an MVC library in its own right, you can pull in single components super easily (for example, you can pull in Zend_Form and Zend_Mail for your contact and feedback forms & validation and use your own models for everything else). This would also give you the extra benefit of having a fallback when/if the time comes when your homebrew MVC framework starts to outgrow its original design. Or, at the very least, speed up your development time so that you're not held up for days because you suddenly realize you need an e-mail model.

Categories