When to separate out functions in php OOP - php

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.

Related

Am I using oop wrongly?

I started learning oop about 6 months ago, although I stopped for a while because of studies.
The problem is that whenever I use oop in my project I usually try to just make every single thing a class... Whether intialization, displaying, looping and much more... to be precise, I haven't gotten the concept of when to use/create classes.
Another problem is that I tend not to know the major benefit of a classes over a functions . Currently, I just mix them up.
I watch a youtube video that talks about classes and client code. In that video they said that classes are more of like developer codes while client codes are codes we write which uses the developer code to make things easier. So he advise we break our code to client/developer code.
But I don't know how to break my code into client code and developer code.
Infact at a point I was creating classes for all my pages like index.php, about.php
<?php
class about{
public $title = 'about page';
public $page_color = 'red';
//functions and more codes
}
After writing the above code I know I am not doing something right. I have tried to search google and have read many oop books but each time they use the car class example which I can not apply to my coding or just wouldn't address the context were a class is or isn't necessary.
Note: I am comfortable building website using procedural codes but I need to learn oop incase I need it someday.
To answer your question: Yes you're using it incorrectly. However it's not a quick fix to get you using it correctly.
There isn't an answer I can give you that will mean you start writing perfect OOP code tomorrow.
You're on the right path, study and practice. Make mistakes, live with those mistakes and refactor them. You'll get sharper the more you do this.
I'm at 16 years experience and I still find new rules and exceptions in OOP. It's not an exact science - it's a method that can yield different results depending on the context.
Just look at all the comments you've had and you'll see no general perfect consensus. Everyone is iteratively improving each others implementation. You can use this approach in your code, keep it tidy and organised, swap bits out as you find better or more correct ways of implementing them.
Well I have not learned php. But I am a good Java developer. And my OOP concepts are good. You mentioned that you do not understand major advantages of classes over function. Both of them are totally different. A class is a blueprint of software.Where as a function represents behaviour of software. You write all the code that does the processing of data provided as input by user and generation of output in functions. Classes contain these functions. The major advantage of writing code in classes is that they can be written in one place and reused anywhere. And OOP concepts are too vast. Each and everything cannot be explained in posts. OOP is much more advantageous than procedural-programming. Consider you are working on a very big project. Some features in the software are common. In OOP you can write code in one place and use them wherever you want.Whereas in procedural-programming you have to rewrite the same code wherever you are using those features. So, your headache of writing code will be minimized in OOP. Also, if the common code works on one place it will obviously work wherever it is being used. This is how OOP evolved from procedural-programming.
OOP is the backbone of most programming languages so you will want to use it basically all the time when you have it fully understood.
Websites are a little trickier to give you good examples of so I'll try and give a generic outline and then a more web-based focus.
Classes should hold data that is related to each-over in a common sense name. For example a Car would obviously hold the Engine (another class), the colour, the name, the owner, etc. And within that the engine would hold it's own set of data that is relative to it (max speed, miles per gallon, etc.). This is the basis of holding your data together, next comes functions within classes.
Now while Car holds data relative to the car, Car also holds functions that the car would do, or functions that the car will use to interact with it's data. Getters(GetColour()) allow outside objects to get information about that specific car (as Car1 and Car2 could hold different colours). Setters are the opposite, to set object specific data. Then we have everything else. Car.start() which internally calls this.engine.start() which may set up some functions to start draining gas from the engine and allow the car to move.
Classes are all about having this easy to read, easy to understand, and easy to re-use. Once your Car class is complete you can re-use as many cars as you need and they are all nicely self-contained.
On to web
Firstly, I highly recommend you look into MVC architecture, which is where the bulk of web architecture is and makes OOP easier to understand for web. Basically your website is split into controllers (in charge of interracting with the DB and giving you back the page), models(Your database data, e.g a user) and your views (HTML with a little templating so your controllers can pass it dynamic data)
For example: You go to website/posts/Stanley , Your Router (another MVC thing) decides that this needs to be handled by the PostsController(a class). The posts controller knows that you want all posts by user Stanley, so it asks the Posts Model(a class)to retrieve all posts by Stanley, the controller then passes these to the view to fill out a template using your Stanley specific posts.
Going away from MVC a second,
With your example given, you will mostly use classes, I would assume, for data manipulation and DB access. For example if you stored blog posts in a database you may have a class Blog with data that matches your db rows (id, user_id, title, body) and functions to access that data to put in your HTML, but also to grab that from the database easily.
For example:
BlogPost::All() may return an array of every blog post newest to oldest.
BlogPost:By(user_id) may return an array of posts by a specific user.
BlogPost:Remove(id) may remove the blog post given it's id.
BlogPost:RatingAtLeast(starRating), get all blog posts with atleast a starRating rating.
You get the idea... This class would exist as you said above, to give you a client code way to access your database that is SPECIFIC to your use case and as BlogPost contains variables related to your BlogPost. So BlogPost::All() will return an array of BlogPost.

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

Custom PHP Framework Feedback

I've been learning OOP programming for about a year and a half now and have developed a fairly standard framework to which I generally abide by. I'd love some feedback or input on how I might improve some functionality or if there are some things I'm overlooking.
VIEW MODE
1) Essentially everything starts at the Index.php page. The first thing I do is require my "packages.php" file that is basically a config file that imports all of the classes and function lists I'll be using.
2) I have no direct communication between my index.php file and my classes, what I've done is "pretty them up" with my viewfunctions.php file which is essentially just a conduit to the classes so that in my html I can write <?php get_title('page'); ?> instead of <?php echo $pageClass->get_title('page'); ?> Plus, I can run a couple small booleans and what not in the view function script that can better tailor the output of the class.
3) Any information brought in via the database is started from it's corresponding class that has direct communication with the database class, the only class that is allowed direct to communicate with the database (allowed in the sense that I run all of my queries with custom class code).
INPUT MODE
1) Any user input is sent to my userFunctions.php.
2) My security class is then instantiated where I send whatever user input that has been posted for verification and validation.
3) If the input passes my security check, I then pass it to my DB class for input into my Database.
php general model http://img139.imageshack.us/img139/3319/phpmodel.gif
FEEDBACK
I'm wondering if there are any glaringly obvious pitfalls to the general structure, or ways I can improve this.
Thank you in advance for your input. I know there is real no "right" answer for this, but I imagine a couple up votes would be in order for some strong advice regarding building frameworks.
-J
One thing I would recommend you do is to go ahead and separate your functions into classes. I understand the points you made about avoiding instantiations but consider this: any framework will, by necessity, begin to accumulate a large number of functions.
Instead of doing
<?php get_title('page'); ?>
you would be better served to create a Page class with all of its functions inside of said class which you call statically. Then, your code becomes
<?php Page::GetTitle('page'); ?>
a much more descriptive naming convention and will become critical later on when trying to avoid naming collisions (you only have to avoid name collisions on say, 50 classes, rather than two thousand functions).
I would study up on the Model-View-Controller design methodology (as ircmaxell hinted at in his post). A lot of very powerful and very well-written frameworks apply this principle, and not just PHP frameworks either. My suggestion - study Yii for how your application should be controlled - very slick and the creator makes excellent use of static variables to control class instantiation.
Good luck with your framework!
Well, the only issue that I can see (without seeing code), is that SQL will be everywhere. What I'd suggest is creating a "model" layer in front of the DB connection class. That way, all your sql is in one spot (break it off into multiple models, etc). It makes maintenance MUCH easier (if you want to add a column to a table, optimize a query, etc)...
Otherwise, it looks like a good start!
Nice presentation. I would definitely look under the hood at other popular frameworks for some insight.
At first glance, I would suggest to see if you can find a way to only load the classes you need per request. Loading them all for every request may become unfeasible if the class library grows large.
Are you using autoloaders? It seems that you will be using a lot of requires... maybe I am just misinterpreting. I think it is great that you are writing your own framework. I don't see it as "reinventing the wheel" either as you are writing it to accomplish the tasks you want to accomplish and can control the overall weight of your project as well as, since you are by most standards still moderately new to OOP, learning a ton I am sure from the experience. Creating your own frameworks, trying to improve other peoples code and learning how others do things and why is an amazing learning experience and in my opinion will drastically improve your programming skills and understanding.

PHP Function Abuse?

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)

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