alternative to MVC that is loosely coupled? - php

I work in a web shop as a PHP programmer. Most of the time we use good coding practices but not much structure to the site as a whole.
I have now entered my phase of being bored with some of our practices and want to branch out and simplify and generate some things in a helpful way not just for me, but the hybrid-programmer web developers in the office.
One employee left us with a MVC site written in PHP, and I have had to maintain it a bit, and I get how it works but have my complaints, my main complaint is that it is tightly coupled with each piece dependent on another. I see the advantage of the seperation of concerns, but this would be confusing to anyone but me looking at the code.
So for example, if I need to add a new page to the site, I have to go add a view, and then add a model, then update the controller. The ad-hoc method of making a new page is way simpler than this and doesn't require a programmer.
My judgement was this was a much better method to build, rather then maintain, a website.
Still, it would be nice if I had some design patterns where I could reuse code effectively without it being dependent on a multiple places in the site.
So my question is, is there a design pattern for building and maintaining websites that is much more loosely-coupled? I'm not looking for slight variations on MVC, I need something quite different to look at, maybe some type of plugin approach.
EDIT:
Thanks for the answers so far! A different way of putting it is I want the code to be done better in my office. Do I A) Push for MVC or B) find/build an alternative not as confusing to the half-programmers. We already use classes for things like DB connectivity and Form helping. The point of this question was to explore B.

There's always a compromise between the code being confusing because it's highly deconstructionist, and the code being confusing because absolutely everything needed to do X is randomly scattered around a single file.
The problem with the latter is that exactly what is an "intuitive" way to split things up into monolithic modules differs between people. Highly decomposed and factored code is nearly always more difficult to wrap your head around, but once you do that, maintenance becomes both easy to do. I disagree that it would be confusing to anyone else but the author looking at it. Large-scope patterns like MVC are used because it becomes easier to spot them and work on projects structured around them over time.
Another advantage of using MVC is that you generally won't make the application more difficult to maintain for someone who comes after you if you don't stick to the layering. This is because now you have a predetermined place where to place any aspect of implementing a new feature.
As far as the tight coupling is considered, you can't really implement a feature without there being some connection between the layers. Loose coupling doesn't mean that the layers are ignorant of each other completely - it means that a layer should be unaware of how the other layers are implemented. E.g.: the controller layer doesn't care whether you're using a SQL database or just writing binary files to persist data at the data access layer, just that there is a data access layer that can get and store model objects for it. It also doesn't care about whether you use raw PHP or Smarty at the view layer, just that it should make some object available under some predetermined names for it. All the while the view layer doesn't even need to know there is a controller layer - only that it gets called with the data to display ready under the abovementioned names provided by /something/.

As frameworks templates go, I find the MVC pattern to be one of the most "loosely coupled" ways of building an application.
Think of the relationships like interfaces, or contracts between the parts of the application. The Model promises to make this data available to the View and the Controller. No one cares exactly how the Model does that. It can read and write from a typical DBMS, like MySQL, from flat files, from external data sources like ActiveResource, as long as it fulfills its end of the deal.
The Controller promises to make certain data available to the View, and relies on the Model to fulfill its promises. The view doesn't care how the Controller does it.
The View assumes that the Models and the Controllers will keep their promises, and can then be developed in a vacuum. The Model and Controller don't care if the view is generating XML, XHTML, JSON, YAML, plaintext, etc. They are holding up their end of the contracts.
And, of course, the View and the Controller need to agree that certain things exist. A View without some corresponding Controller activity might work fine, but could never be used. Even if the Controller doesn't do anything, as might be the case in static pages:
<?php
class StaticController extends ApplicationController
{
/**
* Displays our "about" page.
*/
public function about ()
{
$this->title = 'About Our Organization';
}
}
Then the associated View can just contain static text. (Yes, I have implemented things like this before. It's nice to hand a static View to someone else and say "Just write on this.")
If you look at the relationships between the M, V, and C as contracts or interfaces, MVC suddenly looks very "loosely coupled." Be wary of the lure of stand-alone PHP files. Once you start including and requiring a half-dozen .inc files, or mixing your application logic with your display (usually HTML) you may have coupled the individual pages more loosely, but in the process made a mess of the important aspects.
<?php
/**
* Display a user's profile
*/
require_once 'db.php';
$id = $db->real_escape_string($_GET['id']);
$user_res = $db->query("SELECT name,age FROM users WHERE id = $id;");
$user = $user_res->fetch_assoc();
include 'header.php';
?>
<h1><?php echo $user['name']; ?>'s Profile</h1>
<p><?php echo $user['name']; ?> is <?php echo $user['age']; ?> years old!</p>
<?php
include 'footer.php';
?>
Yeah, "profile.php" and "index.php" are completely unrelated, but at what cost?
Edit: In response to your edit: Push for MVC. You say you have "half-programmers," and I'm not sure which half (do you have front-end people who are good at HTML and CSS but not at server-side? writers with some programming experience?) but with an MVC framework, you can hand them just the views, and say "work on this part."

I have to say that I don't really see your problem with MVC, since your already using templates anyway. I kind of think of it as the pattern that evolves naturally when you try to add structure to an application.
When people first start developing PHP application, the code is usually one big mess. Presentation logic is mixed with business logic which is mixed with database logic. The next step that people usually take is to start using some kind of templating approach. Whether this involves a specialized template language such as smarty or just separating out the presentation markup into a separate file isn't really important.
After this most of us discovers that it's a good idea to use dedicated functions or classes for the database access logic. This really doesn't have to be any more advanced than creating specialized functions for each commonly executed query and placing all those functions in a common include file.
This all seems very natural to me, and I don't believe that it's very controversial. But, at this point you're basicly already using an MVC approach. Everything beyond this is just more or less sophisticated attempts to eliminate the need to rewrite commonly used code.
I understand that this might not be what to you wanted to hear, but I think you should re-evaluate MVC. There's a countless number of implementations, and if it's really the case that none of them suits your needs, then you could always write your own and more basic implementation.
Look at it this way: Since you're already using a template language you'll typically need to create first a regular PHP file, and then a templare file each time you create a new page. MVC doesn't have to be any more advanced than this, and in many cases it isn't. It might even be that all you really need to do is to investigate more sophisticated approaches for handeling data access and add it to your current system.

The fact that you have to create a new Model and Controller Action when you need a new page I don't think means that your M, V, and C layers are tightly coupled. This is just the separation of concerns and contributes to a decoupled system.
That said, it is quite possible to royally screw up the intent of MVC (and I've worked on an app like this) and make it make the components tightly coupled. For instance, a site might put the 'rendering engine' directly in the Controller layer. This would obviously add more coupling. Instead a good MVC will be designed so that the controller is only aware of the name of the view to use and then pass that name to the separate rendering engine.
Another example of bad design in an MVC is when the views have URLs hard-coded into them. This is the job of the Routing engine. The view should only be aware of the action that needs to be called and the parameter that action needs. The Routing engine will then provide the correct URL.

Zend framework is very loosely coupled and is very good. Check it out:
http://framework.zend.com
This article might be of use too:
http://blog.fedecarg.com/2009/02/22/zend-framework-the-cost-of-flexibility-is-complexity/

You can try code Igniter. Its very easy to learn and does not strictly adopt MVC whilst giving your code good structure.

Code Igniter and Kohana (a CI descendent) are OK, but also loosely MVC. I like the simple php framework. It doesn't get in your way and it provides the important stuff, without forcing a structure or complicated conventions on you.

Ah... good old MVC arguments.
I have to maintain a multi-faceted PHP application, pieces of which are written "MVC" style, but not all. Worse, different parts have different ways of doing MVC, all of which are homegrown. And some pages just do it all themselves.
The main problem is not that there is a diversity in framework code, but that the coders clearly did not understand how to abstract APIs. IMO, ths is the biggest problem with MVC frameworks. Almost all of the code I have to work with uses "models" as places to put functions. It is a nightmare to maintain.
To make this maintainable, IME you need a few things:
A distinct and well-defined data-access layer, the API boundary of which looks after retrieving and storing persistent storage and very little else.
I don't like to use the term "model" for that because that is contentious. Whatever calls that layer should not care how the data is stored, should not even be worrying about things like database handles: that is all the job of the data-access layer.
A dispatcher that is very light and doesn't do any magic outside of just dispatching.
Now you can put everything else in one place that accepts requests and parameters, probably normalised and error checked from the dispatcher, fetches the data (usually as objects) it needs, makes the changes it needs to do, saves the data it needs to, hands the data is needs to display to the view. Two hundred lines of code plodding through the task works for this step. You don't need to hive off bits into functions in another file that are called from nowhere else. You can even put the view on the end of this file! Idealism is nice to aspire to but pragmatism needs a look-in because this is maintainable.
(Okay, rant over... )
PHP's lack of enforcing a framework means that the best frameworks do what PHP does: they stay out of the way. Some of the most maintainable code I've worked on had a single require() statement at the top, did all the data-manipulation with data objects (no SQL in sight), then output HTML surrounded by template functions, with form control being done by a consistent function API.

Related

Ajax loading for complex projects

My problem is actually not the ajax loading itself, more the capability to load it without javascript. I mean, I cope easily when I code my whole project just based on ajax-availability OR just without the use of ajax.
//EDIT: Although Arend already had a more or less valid answer, at the same time 'there is no direct answer to this question'. However, I'd like to see some other approaches of developers for scenarios like mine though! Even just a few links can help!
Basically I just get frustrated, coding everything twice on the same page to make sure that both users without and with Javascript enabled have the same experience. It's annoying and I was always wondering how others solve this problem.
When I update for example two divs with dependency on the same variables, it gets messy. Here's an example:
non-js-version
require 'classobject.class.php';
$another_var = 'something';
$class = new classobject($_POST['variable']); // just an example to show that this is dynamic - I'm aware of injection!
$function = $class->returnsth(); // returns 1
if(isset($_POST)) {
echo '<div id="one">Module 1 says:'; $require 'module_one.php'; echo '</div>';
echo '<br /><br />';
echo '<div id="two">Module 2 says:'; $require 'module_two.php'; echo '</div>';
}
Now in module_two.php and module_two.php I have code that executes differently depending on the return variable of $function.
Like:
if($function >= 1 && another_var != 'something') {
// do stuff
}
else {
// do other stuff
}
Now as this works easily with a reload, when I want to load the two modules on keyUp/enter/submit or whatever, I have basically a few problems:
I have to send the $_POST variables manually to the modules to use them
I have to re-execute the class & it's methods and make a link (require_once) to them in each of the module-files.
As $another_var is not existent in the modules, I'd have to send this variable to each modules, too (with post for example) and then before it can be used, I'd have to 'change' it like $another_var = $_POST['another_var'];
I find this mildly annoying and I wonder how you guys do that. I hope my way of coding is not too silly, but I can't think of another way. It's probably hard to relate to my very basic example, but to bring a whole project with the code would be too much. To sum it up, I'm looking for a better way to code and clean this mess up - there must be a way! I thought about sessions, but for compatability I don't want to rely on them either (if someone doesn't allow cookies).
In case you can't relate to what I'm trying to accomplish with that way of having my code assembled, I'll explain a scenario I'm facing quite a lot (not important if you already understand my misery):
Basically I have my index.php page where everything gets executed, with the html body and css styling and so on. This page expects some variables, that get set from the page that requires the index (like $another_var in my example).
Now other variables can get set too (from a form for example). Depending on that different classes and methods load new variables (arrays) that get used in while-loops in my modules to echo everything out.
Hope that's not too abstract. Think of a booking system where some variables are set from the page you are coming from (the event you want to book) and then a few more things get set by the user (a timespan, some preferences,...). In the end it's supposed to show results from the database all the way to the end-result - you can say the user narrows the results from step to step.
There is no direct answer to your question, but there is some food for thought.
Seperation of concerns
You can think about if you can perhaps seperate your buisness logic and layout logic. Often the use of a template engine can help greatly with that. I've had positive experiences with for example Twig or Smarty (was some time ago, not sure how they measure up right now). It requires you to write your code in a (less linear) way, but more logical.
A typical example of an OOP like seperation of concerns might be something like this:
$this->setParam('Myparam','myvalue');
if ($this->isAjax())
{
$this->setTemplate('ajax.php');
$this->setLayout(false);
} else {
$this->setTemplate('normal.php');
$this->setLayout('Mylayout');
}
return $this->render();
It is an imaginative situation, which can be found in many MVC like applications and frameworks. The main idea is that you should have the possibility to seperate your layout from your data. I would suggest looking at some of the modern frameworks for inspiration (like symfony, codeigniter, zend framework).
Glossary / Often applied concepts in a decoupled PHP application
Here is a quick list of concepts that can be used.
Example mvc in php: http://www.phpro.org/tutorials/Model-View-Controller-MVC.html
Note: I don't really like the implementation. I much more prefer the existing frameworks. I do like the explanation in total of this tutorial. E.g. for me this link is for learning, not for implementing.
Silex
For a simple decoupled php micro-framework I would really recommend silex, by the makes of symfony2. It's easy to implement, and to learn, but contains mainy of the concepts described here; and uses all the php 5.3+ goodies such as namespacing and closures.
see: http://silex.sensiolabs.org/
Frontcontroller Pattern
Only have one, and one only point of entry for your code. I usually only have one, and one only point in your application. Usually a frontcontroller 'dispatches' the request to the rest of the application
http://en.wikipedia.org/wiki/Front_Controller_pattern
Routing
A routing system is often used in combination with the frontcontroller pattern. It basically describes which URL is connected to which module / controller. This allows you to change the way people access your app without changing the urls.
See: https://stackoverflow.com/questions/115629/simplest-php-routing-framework
Controller
A controller is the place where buisness logic is applied. Getting the data from the database, checking privileges, setting the template, setting the layout, etc. (although this is also moved outside the controller if it becomes too big of a seperate concern).
Model
The model basically is the layer in which use manage your database. This can be a simple class where you move all your mysql_* functions, or it can be a full-featured ORM. The main philosphy is that all the logic related to fetching and placing information in the database is seperated.
One step up: ORM
An often used method in applications are Object Relational Models, these 'map' SQL records to PHP objects. Doctrine and Propel are two of these well worked out libraries. I heavily rely on these systems in my development. In this sense, the doctrine or propel part will represent the model layer.
Doctrine: http://www.doctrine-project.org/
Propel: http://www.propelorm.org/
Other ORMS: Good PHP ORM Library?
PHP ORMs: Doctrine vs. Propel
View:
The view usually consists of a templating engine. Some use plain PHP as a template, others, such as symfony create a seperate scope in which variables are placed. There are many discussions and opinions about what is best, one is right here on stackoverflow:
Why should I use templating system in PHP?
PHP vs template engine
Ones I like:
- Twig: http://twig.sensiolabs.org/
- sfTemplate: http://components.symfony-project.org/templating/
- Smarty: http://components.symfony-project.org/templating/
Decoupling mechanisms:
Event based systems
Using events in your can help to seperate the code. For example if you want to send an email after a record has been saved, events are a good solution to do that; in general the model should not have to know about email. Thus events are a way to connect them: you can let your -email-send-class listen to certain records in order for them to send the right email. (Perhaps you'd rather want your e-mails send from your controller, this is probably a matter of taste).
Dependency injection
When using OOP code in PHP many relied on having singleton classes running around (configuration, etc). From an OOP point of view, this can be considered bad, because it's hard to test it, and it's not considered very elegant to have dependencies running around like that. Dependency Injection is a pattern that came form Java and is now used in the newer frameworks to get around this. It might be a bit difficult to wrap your head around, but you will see it coming back in several new frameworks.
Dependency injection in php: Dependency Injection in PHP 5.3
Frameworks:
A lot of these methods are difficult, or a lot of work to implement yourself. Many will reside to a framework for this. You may or may not need a framework. You may, or may not want to you a framework, it's your choice. But it's still useful to learn how the frameworks do it, and not try to reinvent the wheel yourself.
The no-framework php frameworks: https://stackoverflow.com/questions/694929/whats-your-no-framework-php-framework
Good habits: https://stackoverflow.com/questions/694246/how-is-php-done-the-right-way
Frameworks worth looking at (imho): CodeIgniter, Kahona, CakePHP, Symfony (1.4/2.0), Silex, Zend Franework, Yii. There are many many more, each with their dedicated fans and haters.
I wrote something like this with PHP. I already had abstracted the rendering of every page such that I define a $content variable and then require('layout.php'). The $content variable is just a big HTML string.
I wrote a PHP function to determine if request was AJAX or not.
The non-AJAX responses render the layout with $content in the middle, b/t header and footer layout content.
AJAX requests basically get this: json_encode(Array("content"=>$content)). And I use jQuery to get the HTML out of the JSON response and modify the DOM. Using json_encode() will handle escaping the string for javascript.
In the end, I effectively have AJAXified every page w/o over-engineering a complex solution.
Any browser that supports AJAX can also open a link in a new tab/window to simulate the non-AJAX request. (Or bookmark/share a link, too.)

Breaking away from MVC

Lately I've been trying to improve upon/move away from the standard MVC setup for web development, and I thought it was about time to throw my ideas at StackOverflow.
The general flow is the same in that a bootstrapper creates the initial objects. The difference is that these are then kept in a ServiceManager.
Then, instead of dispatching a controller, it loads the view.
The view then calls Commands and Queries. Commands represent functionality that is generally form-related (updating database rows, generally), and Queries are what normally would be ModelPeers. When these are created (via the ServiceManager) they have the ServiceManager passed to them, which gets rid of the need for a lot of potentially complicated dependency injection.
The models themselves would just do create/update/delete on a single row.
So a view would look like:
ListUsers.php
<?php $users = $this->ServiceManager->get('Query\User')->getNewestUsers(10); ?>
<?php foreach($users as $user): ?>
....
<?php endforeach; ?>
UpdateUser.php
<?php $this->ServiceManager->get('Command\User')->update(); ?>
<form>...</form>
I know that there's some tier violation, but it seems a lot cleaner than having a bunch of controllers that act more like ViewVariableSetters than anything.
It also makes everything much more testable since all functionality is encapsulated into Commands and Queries and away from large controllers. Technically, I could have a controller or ViewVariableSetter, but it seems like it would add a lot more code with very little benefit.
Any feedback would be appreciated, and please let me know if I can clarify anything.
You will feel that little benefit once you add another developer to your project and when your project goes bigger and bigger. You'll be thankful you separated the view from the controller and from the model.
If you don't like MVC, you could look at its siblings MVP (Model-View-Presenter), PM (Presentation Model) and MVVM (Model-View-ViewModel).
In fact, what you describe may be PM, I'm not sure.
One good start here: making reusable / modular code to be called from a controller, rather than the giganto monolithic controller.
My opinion: perhaps the problem is not so much "MVC", as current dogma about the "V" (view). Current dogma seems to be that the view must be a (HTML) template, in which code has to be woven into an "object d' art". One could argue that for many applications, this is just make-work.
Perhaps we need better / alternate "view" technology: when setting up a CRUD edit task, as opposed to a marketing kiosk (which should be a work of art), we make an API to generate forms and other UI elements using a "DOM" model like javascript in the browser (or like java AWT)? Just a thought.
In response to comment:
"... I want to avoid having a class that just passes stuff to a view ..."
First off, it should be doable to make this a minimum amount of code when it is a minimum amount of work. For instance, I like how "Rails" automatically routes requests within a certain "region" of the application into a class, mapping requests to individual functions/handlers. I've emulated this behaviour in java code, to keep responses more concise.
Second, this "passing info to a view" is just a specific instance of "calculate and store, passing data along a pipeline of simple steps". It makes code easier to understand and maintain. I'm not a hardcore "functional programming" fan, but there is something to be said for being able to (easily) comprehend the data flow in a piece of code. As a side benefit, it often (unintuitively, it seems) makes code actually run a bit faster as well. I've ranted about "locality" before, so I won't repeat it here.
How will you adjust the view to accomodate to different formats? Eg html response, json response etc.
MVC is a bit of a curious design for the web. Most of the time, you don't really need the separation between view and controller. On the other hand, because url's act as application state, you need some level of interoperability between the two. This leads to one of two scenarios; Either you only get a partial separation, or you get a lot of complexity. Neither is very beneficial.
I'd say that most frameworks choose a relaxed separation. Rails and its php clones generally follow this strategy. Personally I don't really see the point of that. A two-layered (eg. model/presentation) design can work well for the majority of applications.
There is something to be said though for using an industry standard - however wrong - simply because it's a standard. If you cook your own architecture up, other developers will have a harder time figuring it out. You shouldn't underestimate how much work there goes into getting something like that just right.

PHP: A Personal Framework

I'm going to write a framework for my web projects in PHP.
Please don't tell me about considering to use some existing framework (Cake, CodeIgniter, Symfony, etc.) - I have already had a look at them and decided to write one for myself.
The framework itself will mainly consist of a module system, a database handler and a template parser. (Many other things too, of course)
With module system I mean that every module has exactly one PHP file and one or more templates associated with it.
An example module would be modules/login.php that uses templates/login.tpl for its design.
These days everyone(?) is talking about the MVC (Model View Controller) concept and most of the existing frameworks use it, too.
So my questions are the following:
Is MVC really effective for a personal framework?
Would it be a bad idea to use a module system?
Did you ever write a framework for yourself? What are your experiences?
Is MVC really effective for a personal framework?
Yes, it can be. Although, it might be a little overkill (which, is not necessarily a bad thing if you are trying to learn)
Would it be a bad idea to use a module system?
This is never a bad idea.
Did you ever write a framework for yourself? What are your experiences?
I wrote a common security framework for my group's PHP applications when I was an intern. I learned alot, but the project as a whole might have benefited more from a pre-built solution.
Of course, I wouldn't have learned as much if I just installed a pre-built solution. So you always have to take that into account, especially for personal projects. Sometimes re-inventing the wheel is the only way you will learn something well.
Is MVC really effective for a personal framework?
What MVC means anymore, due to its vague interpretation, is business logic, presentation, and input handling. So, unless you aim to design an application that does not involve any three of those, MVC is, in its vague sense, very suitable.
Often it can be more formal than you desire, however, as it demands physical separation of ideas into different code files. Quick and dirty tasks or rapid prototyping might be more quickly setup if the formalities are avoided.
In the long term, what MVC asks for is beneficial to the sustainability of the application in ways of maintenance and modification or addition. You will not want to miss this. Not all frameworks encourage the right practices, though. I am not surprised that you find the various implementations you've tried insufficient. My personal favourite is Agavi. To me and others, in a world of PHP frameworks that do not feel right, Agavi emerges to do the right things. Agavi is worth the shot.
Would it be a bad idea to use a module system?
MVC asks you to separate components of business logic, presentation, and input handling, but it does not suggest how to layout the files. I presume this is the challenge you are addressing with a module system. To answer your question: modules serve identically to sub-directories. If the items are few, its probably more hassle to bother with subdirectories even if the files could logically be separated into them. When the number of items grow large, its now cumbersome to locate them all and sub-directories become a better option.
Frameworks will tack on functionality that allows you to deal with modules as their own configurable entity. The same functionality could just as well exist without modules, perhaps in a more cumbersome manor. Nonetheless, do not consider modules primarily as a system. Systems are so wonderfully vague that you can adapt them to whatever setup you find suitable.
Did you ever write a framework for yourself? What are your experiences?
Yes I have wrote several frameworks with various approaches to solving the issues of web applications. Every such framework I wrote became nothing but a vital learning curve. In each framework I made I discovered more and more the issues with building software. After failing to create anything interesting, I still gained because when asked to make a program I could fully do so with justice.
I recommend you continue if this is the sort of learning experience you want. Otherwise, give Agavi a shot. If that too fails, ensure that you have a clear and detailed specification of what your framework will do. The easiest way to barge into making software, work really hard, and accomplish nothing is to not decide before-hand what exactly your software will do. Every time I ran into making code the only thing in my mind was I will do it right. What happened was a different story: oh, well I need to make a routing system as that seems logical; hmm, okay, now I need a good templating system; alright, now time for the database abstraction; but gee, what a lot of thinking; I should look to the same system from software XXY for inspiration. Therein is the common cry that pleads to use existing software first.
The reason I thought I could do it right was not because all the nuts and bolts of the framework felt wrong. In fact, I knew nothing about how right or wrong they were because I never worked with them. What I did work with was the enamel, and it felt wonky. The quickest way to derive your own framework is really to steal the nuts and bolts from another and design your own enamel. That is what you see when building an application and frankly is the only part that matters. Everything else is a waste of your time in boilerplate. For learning how to build software, however, its not a waste of time.
If you have any other questions, please ask. I am happy to answer with my own experience.
I am also actually writing a php framework with a friend of mine. I absolutely can understand what you do.
I thing what you are doing is near mvc. You have the templates as views. And the modules as controller. So I think that is ok. The only thing you need is the model. That would be some kind of active records.
In my framework there are simular concepts, except we are writing our own active records engine at the moment. I think what you do isn't bad. But it's hard to say without seeing code.
I see only one problem you have to solve. A framework should be perfectly integrated. It is always a complicated to make your module look nice integrated without always have to think of module while you are coding application.
Is MVC really effective for a personal framework?
Would it be a bad idea to use a module system?
Yes it is. But MVC is such a loosy-goosy design pattern that you can draw the line between model, view, and controller anywhere you want. To me, the most important parts are the model and the view. I simply have pages, php modules, that generate html by filling in a template from a database. The pages are the view and the database is the model. Any common application-specific code can be factored out into "controllers". An example might be a common, sophisticated query that multiple pages must use to render data.
Other than that I have utilities for safe database access, simple templating, and other stuff.
Did you ever write a framework for yourself? What are your experiences?
Yes. I'm very glad I did. I can keep it simple. I know intimately how it works. I'm not dependent on anyone but myself. I can keep it simple yet useful.
Some pointers (0x912abe25...):
Every abstraction comes with a cost.
Don't get to fancy. You might regret not keeping it simple. Add just the right amount of abstraction. You may find you over-abstracted and something that should be simple became excessively complex. I know I've made this mistake. Remember You-aint-gonna-need-it.
Scope your variables well
Don't load your pages by doing
include_once('...page file ...');
where it's expected that page file will have a bunch of inline php to execute looking up different global variables. You lose all sense of scope. This can get nasty if you load your page file from inside a function:
function processCredentials()
{
if (credentialsFail)
{
include_once('loginpage.php');
}
}
Additionally, when it comes to scoping, treat anything plugged into templates as variables with scope. Be careful if you fill in templates from something outside the page file associated with that template (like a master index.php or something). When you do this it's not clear exactly what's filled in for you and what you are required to plug into the template.
Don't over-model your database with OO.
For simple access to the database, create useful abstractions. This could be something as simple as fetching a row into an object by a primary index.
For more complex queries, don't shy away from SQL. Use simple abstractions to guarantee sanitization and validation of your inputs. Don't get too crazy with abstracting away the database. KISS.
I would say that MVC makes more sense to me, since it feels better, but the only practical difference is that your login.php would contain both the model (data structure definitions) and the controller (code for page actions). You could add one file to the module, e.g. class.login.php and use __autoload() for that, which would essentially implement an MVC structure.
I have refactored a big PHP project to make it more MVC compliant.
I found especially usefull to create a DAO layer to centralize all database accesses. I created a daoFactory function, which creates the DAO and injects the database handle into it (also the logger, I used log4php, got injected).
For the DAO, i used a lot the functionalities of the database (mysql), like stored procedure and triggers. I completly agree with Doug T. about avoid over-abstraction, especially for database access : if you use the DB properly (prepared statements, etc.) you don't need any ORM and your code will be much faster. But of course you need to learn mysql (or postgress) and you become dependant on it (especially if you use a lot of stored procedure, like I tend to do).
I am currently refactoring a step further, using the Slim php framework and moving toward a restfull api : in this case there is no view anymore because everything is outputted as json. But I still use smarty because its caching works well and I know it.
Writing a framework could be a rewarding experience. The important thing to consider is that you do not write a framework for its own sake. The reason one writes a framework is to make development easy.
Since it is a personal framework you should think in terms of how it could help you develop with less hassle.
I do not think a template system is a good idea. Think of it - what is the major benefit of using a template system? The answer is that it helps teams with different skill sets jointly develop an application. In other words, some members of the team can work on the user interface and they do not need to be PHP coders. Now, a personal framework will most likely be used by a single person and the benefit of template system becomes irrelevant.
All in all, you should look at your own coding habits and methods and discover tasks that take most of your time on a typical project. Then you should ask yourself how you can automate those tasks to require less time and effort. By implementing those automation mechanisms you will have to stick to some sort of conventions (similar to an API). The sum of the helper mechanisms and the conventions will be your personal framework.
Good luck.
MVC doesn't work
you don't want to be constrained in the structure of your "modules"; also, keep templates close to the code (the templates directory is a bad idea)
no
re 1.: see Allen Holub's Holub on Patterns. briefly: MVC basically requires you to give up object oriented principles.
Tell Don't Ask is a catchy name for a mental trick that helps you keep the data and code that acts on it together. Views cause the Model to degrade into a heap of getters and setters, with few if any meaningful operations defined on them. Code that naturally belongs in the Model is then in practice spread among Controllers and Views(!), producing the unhealthy Distant Action and tight coupling.
Model objects should display themselves, possibly using some form of Dependency Injection:
interface Display
{
function display($t, array $args);
}
class SomePartOfModel
...
{
function output(Display $d)
{
$d->display('specific.tpl', array(
'foo' => $this->whatever,
...
));
}
}
OTOH, in practice I find most web applications call for a different architectural pattern, where the Model is replaced with Services. An active database, normalized schema and application specific views go a long way: you keep the data and code that acts on it together, and the declarative nature makes it much shorter than what you could do in PHP.
Ok, so SQL is a terribly verbose language. What prevents you from generating it from some concise DSL? Mind you, I don't necessarily suggest using an ORM. In fact, quite the opposite. Without Model, there's little use for an ORM anyway. You might want to use something to build queries, though those should be very simple, perhaps to the point of obviating such a tool...
First, keep the interface your database exposes to the application as comfortable for the application as possible. For example, hide complex queries behind views. Expose update-specific interfaces where required.
Most web applications are not only the owners of their respective underlying databases, they're their only consumers. Despite this fact, most web applications access their data through awkward interfaces: either a normalized schema, bare-bones, or a denormalized schema that turned out to make one operation easier at the price of severe discomfort elsewhere (various csv-style columns etc). That's a bit sad, and needlessly so.
re 2.: it's certainly good to have a unified structure. what you don't want to do is to lock yourself into a situation where a module cannot use more than one file.
templates should be kept close to code that uses them for the same reason that code that works together should be kept together. templates are a form of code, the V in MVC. you'll want fine-grained templates to allow (re)use. there's no reason the presentation layer shouldn't be as DRY as other parts of code.

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.

is my php architecture solid?

I'm trying to design a solid server side architecture and came up with this :
http://www.monsterup.com/image.php?url=upload/1235488072.jpg
The client side only talks to a single server file called process.php, where user rights are checked; and where the action is being dispatched. The business classes then handle the business logic and perform data validation. They all have contain a DataAccessObject class that performs the db operations.
Could you point the different weaknesses such an architecture may have? As far as security, flexibility, extensiveness, ...?
Your architecture isn't perfect. It never will be perfect. Ever. Being perfect is impossible. This is the nature of application development, programming, and the world in general. A requirement will come in to add a feature, or change your business logic and you'll return to this architecture and say "What in the world was I thinking this is terrible." (Hopefully... otherwise you probably haven't been learning anything new!)
Take an inventory of your goals, should it be:
this architecture perfect
or instead:
this architecture functions where I need it to and allows me to get stuff done
One way that you could improve this is to add a view layer, using a template engine such as Smarty, or even roll-your-own. The action classes would prepare the data, assign it to the template, then display the template itself.
That would help you to separate your business logic from your HTML, making it easier to maintain.
This is a common way to design an application.
Another thing you could do is have another class handle the action delegation. It really depends on the complexity of your application, though.
The book PHP Objects, Patterns and Practice can give you a real leg-up on application architecture.
I see a couple of things.
First, I agree with others that you should add a view layer of some kind, though I am not sure about Smarty (I use it frequently and I am really having doubts these days, but I digress). The point is you need to separate your HTML somewhere in a template so it's easy to change. That point does not waver if you use a lot of AJAX. AJAX still requires you (usually) to put divs around the page, etc. So your layout should be separated from processing code.
The second thing I would throw out there is the complexity of your data model matters. If this is a straightforward CRUD application over an existing, or fairly flat, db model, you are probably fine with these db access classes. But, the minute your model gets to be more complex, with hierarchies or polymorphic in any way, this will break down. You'll need a more robust ORM of some kind.
Your "controller/dispatcher" methodology seems sound. The switch statements avoids the need for any kind of URL -> code mappings, which are a pain to manage and require caching to scale.
That's my $0.02
From a security perspective your class and action are coming in from your post variables and this can be dangerous because you should never trust anything coming from the user. Assumingly your class/action will look something like this:
class1
{
action1.1
action1.2
...
action1.N
}
class2
{
action2.1
action2.2
...
action2.N
}
As an attacker my first place to look would be getting into a state where an action doesn't match to it's appropriate class. I would try to submit class1 with action2.1 instead of action1.1.
With that said, my assumption is that you've already got some form of validation and so this wouldn't happen. Which leads me to my original post: If your architecture works for you, then it works for you. Take a look at the things which you're asking about: security, flexibility, extensibility and evaluate them yourself. Find your own flaws. If you don't know how to evaluate for security/flexibility/other read up on the subject, practice it and apply it.
You'll become a better developer by making mistakes and then learning from them (except missile guidance software, you only get one try there.)
Since others have suggested various changes like adding a view layer, etc. let me concentrate on the various criteria for a good architecture:
Extensibility: Usually, the more abstract and loosely coupled the architecture is, the more extensible it is. This is exactly why others have recommended you use a view layer which would abstract out the presentation layer templates for each class:action pair into its own file.
Maintainability: This goes hand-in-hand with extensibility. Generally, the more extensible the architecture is, the more maintainable it is (take that with a grain of salt because it is not always the case). Consider adding a model layer below your model logic layer. This would help you swap out your data access logic from the model business logic.
Security: The downside to the architecture you have posed is that you really need to invest in security testing. Since all your redirecting/routing code is in process.php, that file has a lot of responsibility and any changes to it may result in a potential security loophole. This isn't necessarily wrong, you just need to be aware of the risks.
Scalability: Your architecture is balanced and seems very scalable. Since you have it broken down by class:actions, you can add caching at any layer to improve performance. Adding an addition data access model layer will also help you cache at the layer closest to the database.
Finally, experiment with each architecture and don't be afraid to make mistakes. It already seems like you have a good understanding of MVC. The only way to get better at architecting is to implement and test it in the 'real world'.

Categories