PHP Function Abuse? - php

I have a large system that I have coded and I wish to make the code (dare I say) more simple and easy to read. Unfortunately before this, I haven't used functions much.
I have many different MySQL Queries that are run in my code, I feel that if I make the various displays into functions and store them in a separate file it would make the code much easier to maintain (actually, I know it would).
The only thing I am wondering is, if this is a common practice and if you think that it is going to hurt me in the long run in terms of performance and other factors. Here is an example of what I currently am using:
$result = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_array($result)){
/* Display code will go here */
}
As you can imagine this can get lengthy. I am thinking of making a function that will take the result variable, and accomplish this, and then return the results, as so:
$result = mysql_query("SELECT * FROM table");
dsiplayinfo($result);
Do you think this is the right way to go?
[Edit]
The functions would be very different because each of them needs to display the data in different ways. There are different fields of the database that need to be shown in each scenario. Do you feel that this approach is still a good one even with that factor? AKA Modular design is not being fully accomplished, but easy maintenance is.

One thing you want to keep in mind is the principle of DRY: Don't Repeat Yourself.
If you are finding there is a block of code that you are using multiple times, or is very similar that can be made the same, then it is a ideal candidate for being moved into a function.

Using more functions can be helpful, and it can be hurtful. In theory it moves you more towards modular design, meaning you can use a function over and over in multiple apps without having to re-write it.
I would honestly encourage you to more toward larger conventions, like the MVC Frameworks out there. Kohana is a great one. It uses things like Helpers for additional outside functionality, Models to query the database, and Controllers to perform all of your logic - and the end-result is passed on to the View to be formatted with HTML/CSS and spiced up with Javascript.

Don't use "SELECT *" -- enumerate the fields you want for performance reasons, as well as maintainence reasons.
In your example, the display code will likely be pretty closely coupled with the SQL query, so you may as well encapsulate them both together
You might consider some sort of MVC framework with an ORM (like CakePHP) which will facilitate Model reuse much better than writing a bunch of functions
You are on the right track! Write your code, then refactor it to make it better--very smart.

Yes, also consider looking into an ORM or some database agnostic interface. This might help reduce duplication as well (and certainly make porting to a new DB easier, should that ever come up).
Basically any time you see similar looking code (be it in structure or in functionality) you have an opportunity to factor it out into functions that can be shared across the application. A good rule of thumb is Don't Repeat Yourself (DRY)

Related

When to separate out functions in php OOP

I'm coding an interface class at the moment to manage showing of user comments on two different kinds of pages, one page is the profiles and the other is the media pages.
Both sets of comments are stored in different tables but I'm wondering whether I should use one function or split both tables into a separate function.
Is the overall goal of OOP to have code that works well for your site or to be able to use it over in different sections without the need to modify lots?
I could have:
showComments($pageId, $type, $userType)
{
if($type == 'media')
$sql = "SELECT comment FROM mediatable WHERE id=:pageId";
elseif($type == 'profile')
$sql = "SELECT comment FROM profileTable WHERE id=:pageId";
if($userType == 'moderator')
//show Moderation Tools
//Rest of code goes here
}
Or I could seperate it into different functions like so:
showMediaComments($id);
moderateMediaComments($id);
showProfileComments($id);
moderateProfileComments($id);
I'm thinking the second method would be better as I could then use the code again easier but it would required more lines of code ...
Neither one is proper OOP. A proper way would be to have a abstract Comment class and subclasses MediaComments, ProfileComments that handle the differences. Also, read about the MVC architecture
It really depends on what your goal is for your OOP site.
Many people use OOP to different extents and in many different ways, however, if you're using a true MVC, it would have a model class for each database table, so mediatable and profiletable queries wouldn't be in the same function.
That said, in my opinion, separating them would be better. It tends to keep code cleaner and more localized.
Is the overall goal of OOP to have code that works well for your site
or to be able to use it over in different sections without the need to
modify lots?
The overall goal of OOP is to design systems that are more flexible to future changes by providing interfaces and classes which can be optionally extended by future developers to meet needs not originally accounted for.
The goal of modular design (in procedural or OOP code) is to create small chunks of code that represent each logic bit which is it's own independent block (i.e. function/method). In other words, each logical task should be broken down into the individual components that make it up in the same way you would normalize a database table in a RDBMS.
Is the overall goal of OOP to have code that works well for your site
Think about it, OOP or not, you'll always want code that works well for your site :)
or to be able to use it over in different sections without the need to modify lots?
I agree pretty much with the answer from #Xeoncross for this one, but I like to view OOP from a more conceptual point of view: objects that collaborates throught message sends with the goal of modelling a subset of the reality (that is, your domain problem). I found it easier to think in terms of domain concepts instead of classes and interfaces (that's the way you use to express those domain concepts).
About the sample you posted, it's good to separate each branch of the conditional in its own method.
To learn why the previous is important, let´s take the following example: suppose there´s a bug in the media comments part of then code (and rest is working fine). For fixing it, you'll have to modify that part, potentially making changes that breaks already working code just because all belongs to the same method (remember, "If it ain't broke, don't fix it").
Follow #Darhazer advice and put each pice of logic in the class where it belongs. That way a class will only know about one and only one thing (MediaComments contains only the code that deals with media comments, ProfileComments does the same for profile comments, and so on). That will make it easy to locate, maintain and modify code related to a particular concept.
You can learn more about the reasons behind this decision reading about The Single Responsibility Principle here and here.
Also, I think you'll find interesting the "Replace Conditional with Polymorphism" section of Martin Fowler's book: Refactoring: Improving the Design of Existing Code that explains the drawbacks of having a conditional statement like yours and gives you an object oriented technique to get rid of it.
It depends, but generally speaking you should try to separe chunk of code and do a simple task with each method. What will happen if you add another type of media in the future - you will end up adding "if elses" to this method.

Pile of little functions that call each other. Better way to organize my code?

I'm a beginner but I've written my first little project and something about it doesn't really feel right. I hope I can describe the problem clearly.
My whole program is basically a pile of little functions that call each other, and then one or two lines of code that call the initial function to start off the 'chain reaction' and return the desired result.
It looks kind of like this (I'm using PHP):
$result = func_A($args);
function func_A($arg1, $arg2){
$localvar1 = blah blah;
$value = func_B($localvar1, $arg2);
return $value;
}
function func_B($arg1, $arg2){
$localvar1 = blah;
$value = func_C($localvar1, $arg2);
$return value;
}
function func_C($args){
blah blah blah
}
So when I try to go through my code, I'm hopping around all over the place between functions like crazy.
Is there a better way to do this? Should I just be creating local functions within my other functions? This just doesn't feel quite right.
Overall this is fine. We'd need to know more about specific goals and what the code is doing to get into more detail. In general, keeping the nuts and bolts in functions and calling them from a sort of main "command" center is a fine approach to procedural programming.
However, some general high level rules that work for me:
Don't repeat yourself. If you find you're doing the same things over
and over again, make a function of that. If you load a value from a
file, calculate something with it, and echo that, make a function for
it.
Don't overspecialize too far. Lots of 2 line functions probably
isn't a good thing.
If you can, be general. Don't make 5 different functions to connect
to 5 different databases. Make one function and pass the name of the
database to connect to it. See the rule about not repeating
yourself.
If you have one function that calls another that calls another, and
they are always used that way, consider making a single function of
them.
Objects are great for dealing with a set of values and doing things with them. For a quick script, not so much, but if you're going to do some substantial work like validating data, storing it, reading it in, making it into a single string, that's a good opportunity to make a class. Classes will conveniently fit into a file which you can then use in other projects as well, and if you do maintenance to this class often, the scripts that use it may not need to be changed at all if your initial design was solid.
There is nothing inherently wrong (and in fact a lot right) with this approach, if you're doing procedural programming (as it appears you are).
PHP does now support Objects (albeit in a fabulously ugly way, in my opinion) so, there may be an argument for modifying your code to be more OO. However, it makes sense to isolate various tasks into small individual functions that you can then edit.
I know this is somewhat controversial, but if you're just starting out in PHP, unless it's a core requirement of your client/employer, I would bypass it entirely and look into Node.js.
There's a great deal of benefit that you get from using one language on both sides of the client/server isle, rather than dividing tasks into two similar looking but different languages, which constantly share screen real-estate as you work on them, owing to how much of a hassle it is to keep the server and display portions of the code truly separate.
Of course PHP has become so entrenched that many people see it as a foregone conclusion. But (in my irrelevant opinion) all fandom aside, it has many shortcomings and is really ripe for retirement.
You can use references to avoid repetitions. Add your functions name to an array and when you need a solution you have a main function that loops through that array and call the function with $this->$function_name.

Why should I abstract my data layer?

OOP principles were difficult for me to grasp because for some reason I could never apply them to web development. As I developed more and more projects I started understanding how some parts of my code could use certain design patterns to make them easier to read, reuse, and maintain so I started to use it more and more.
The one thing I still can't quite comprehend is why I should abstract my data layer. Basically if I need to print a list of items stored in my DB to the browser I do something along the lines of:
$sql = 'SELECT * FROM table WHERE type = "type1"';'
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result))
{
echo '<li>'.$row['name'].'</li>';
}
I'm reading all these How-Tos or articles preaching about the greatness of PDO but I don't understand why. I don't seem to be saving any LoCs and I don't see how it would be more reusable because all the functions that I call above just seem to be encapsulated in a class but do the exact same thing. The only advantage I'm seeing to PDO are prepared statements.
I'm not saying data abstraction is a bad thing, I'm asking these questions because I'm trying to design my current classes correctly and they need to connect to a DB so I figured I'd do this the right way. Maybe I'm just reading bad articles on the subject :)
I would really appreciate any advice, links, or concrete real-life examples on the subject!
Think of a abstracting the data layer as a way to save time in the future.
Using your example. Let's say you changed the names of the tables. You would have to go to each file where you have a SQL using that table and edit it. In the best case, it was a matter of search and replace of N files. You could have saved a lot of time and minimized the error if you only had to edit one file, the file that had all your sql methods.
The same applies to column names.
And this is only considering the case where you rename stuff. It is also quite possible to change database systems completely. Your SQL might not be compatible between Sqlite and MySQL, for example. You would have to go and edit, once again, a lot of files.
Abstraction allows you to decouple one part from the other. In this case, you can make changes to the database part without affecting the view part.
For very small projects this might be more trouble than it is worth. And even then, you should still do it, at least to get used to it.
I'm NOT a php person but this is a more general question so here goes.
You're probably building something small, sometimes though even something small/medium should have an abstracted data layer so it can grow better.
The point is to cope with CHANGE
Think about this, you have a small social networking website. Think about the data you'll store, profile details, pictures, friends, messages. For each of these you'll have pages like pictures.php?&uid=xxx.
You'll then have a little piece of SQL slapped in there with the mysql code. Now think of how easy/difficult it would be to change this? You would change 5-10 pages? When you'll do this, you'll probably get it wrong a few times before you test it thoroughly.
Now, think of Facebook. Think of the amount of pages there will be, do you think it'll be easier to change a line of SQL in each page!?
When you abstract the data access correctly:
Its in one place, its easier to change.
Therefore its easier to test.
Its easier to replace. (Think about what you'd have to do if you had to switch to another Database)
Hope this Helps
One of the other advantage of abstracting the data layer is to be less dependent on the underlying database.
With your method, the day you want to use something else than mysql or your column naming change or the php API concerning mysql change, you will have to rewrite a lot of code.
If all the database access part was neatly abstracted, the needed changes will be minimal and restricted to a few files instead of the whole project.
It is also a lot easier to reuse code concerning sql injection or others utility function if the code is centralized in one place.
Finally, it's easier to do unit testing if everything goes trough some classes than on every pages from your project.
For example, in a recent project of mine (sorry, no code sharing is possible), mysql related functions are only called in one class. Everything from query generation to object instantiation is done here. So it's very for me to change to another database or reuse this class somewhere else.
In my opinion, the data access is one of the most important aspects to separate / abstract out from the rest of your code.
Separating out various 'layers' has several advantages.
1) It neatly organises your code base. If you have to make a change, you'll know immediately where the change needs to be made and where to find the code. This might not be so much of a big deal if you're working on a project on your own but with a larger team the benefits can quickly become obvious. This point is actually pretty trivial but I added it anyway. The real reason is number 2..
2) You should try to separate things that might need to change independently of each other. In your specific example, it is conceivable that you would want to change the DB / data access logic without impacting the user interface. Or, you might want to change the user interface without impacting on the data access. Im sure you can see how this is made impossible if the code is mixed in with each other.
When your data access layer, has a tightly defined interface, you can change its inner workings however you want, and as long as it still adheres to the interface you can be pretty certain it wont have broken anything further up. Obviously this would still need verifying with testing.
3) Reuse. Writing data access code can get pretty repetitive. It's even more repetitive when you have to rewrite the data access code for each page you write. Whenever you notice something repetitive in code, alarm bells should be ringing. Repetitiveness, is prone to errors and causes a maintenance problem.
I'm sure you see the same queries popping up in various different pages? This can be resolved by putting those queries lower down in your data layer. Doing so helps to ease maintenance; whenever a table or column name changes, you only need to correct the one place in your data layer that references it instead of trawling through your entire user interface and potentially missing something.
4) Testing. If you want to use automated tool to carry out unit testing you will need everything nicely separated. How will you test your code to select all Customer records when this code is scattered all throughout your interface? It is much easier when you have a specific SelectAllCustomers function on a data access object. You can test this once here and be sure that it will work for every page that uses it.
There are more reasons that I'll let other people add. The main thing to take away is that separating out layers allows one layer to change without letting the change ripple through to other layers. As the database and user interface are areas of an application / website that change the most frequently it is a very good idea to keep them separate and nicely isolated from everything else and each other.
In my point of view to print just a list of items in a database table, your snippet is the more appropriate: fast, simple and clear.
I think a bit more abstraction could be helpful in other cases to avoid code repetitions with all the related advantages.
Consider a simple CMS with authors, articles, tags and a cross reference table for articles and tags.
In your homepage your simple query will become a more complex one. You will join articles and users, then you will fetch related tag for each article joining the tags table with the cross reference one and filtering by article_id.
You will repeat this query with some small changes in the author profile and in the tag search results.
Using a abstraction tool like this, you can define your relations once and use a more concise syntax like:
// Home page
$articles = $db->getTable('Article')->join('Author a')
->addSelect('a.name AS author_name');
$first_article_tags = $articles[0]->getRelated('Tag');
// Author profile
$articles = $db->getTable('Article')->join('Author a')
->addSelect('a.name AS author_name')->where('a.id = ?', $_GET['id']);
// Tag search results
$articles = $db->getTable('Article')->join('Author a')
->addSelect('a.name AS author_name')
->join('Tag')->where('Tag.slug = ?', $_GET['slug']);
You can reduce the remaining code repetition encapsulating it in Models and refactoring the code above:
// Home page
$articles = Author::getArticles();
$first_article_tags = $articles[0]->getRelated('Tag');
// Author profile
$articles = Author::getArticles()->where('a.id = ?', $_GET['id']);
// Tag search results
$articles = Author::getArticles()
->join('Tag')->where('Tag.slug = ?', $_GET['slug']);
There are other good reasons to abstract more or less, with its pros and cons. But in my opinion for a big part the web projects the main is this one :P

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.

alternative to MVC that is loosely coupled?

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.

Categories