Related
I have been writing a lot of code for work in PHP/MySQL. So far it has all been procedural making use of functions for functionality occuring multiple times/places. Starting to find some of the site hard to manage - time to go OO.
I want to learn about MVC with object oriented PHP & MySQL. I have some experience in Java and MVC but never anything to do with web technologies, i.e. HTML/CSS/JS etc. I don't really understand how the dynamically generated HTML fits in with the classes etc.
I am after some recommndations about where I can start. Ideally some sites with great examples from the ground up. I don't really want to use a framework at this point because I find that it does too much for you. Once I understand the OO approach with MVC I'll probably use a framework to managei easier.
Cheers,
Evan
You have a lot of code, and despite being hard to change, it probably works. Making an overhaul is going to set you back a while, so the best approach is incremental. Find some ONE thing that would seriously benefit from using objects, and use objects there. Refactor as you are able to run tests. You can work this in with the ordinary flow of events, and things work out OK.
Frankly, if you're serious about removing redundancy and duplication, you'll often find places where just writing a small function can make a dent. If you do this often enough, you'll find groups of functions that work on the same data. That will suggest where to look for objects.
In other words, if you listen with the right kind of ears, the code will tell you.
If you just want a good online course, maybe you should have a look at
http://www.lynda.com/home/DisplayCourse.aspx?lpk2=653&srchtrk=index%3A1%0Alinktypeid%3A2%0Aq%3APHP%20Object%20Oriented%0Apage%3A1%0As%3Arelevance%0Asa%3Atrue%0Aproducttypeid%3A2%0Acategory_facet%3APHP
This course was really useful for a friend of me. The progress he booked when he finished this tutorial was really great. It takes you through the basics of building a CMS in PHP and object oriented.
I think you should start with small pieces to get into OOP step by step. I mean that you should write simple classes for things you use often like handling forms, image uploads, site messages, session handling.
When you get used to programming classes and working on objects it will be time to jump for something bigger like refactor whole "engine" to OOP using mvc and other stuff.
Not really an answer but too big to be a comment.
Actually HTML has nothing to so with classes and JS and CSS has nothing to do with PHP, MVC and OOP at all.
Your code should produce some data which is going to be displayed one or another way. You can use some class to render this data, but it's not that important class.
While JS and CSS are totally separate files usually, called by browser directly from the server, avoiding your application code (unless being generated dynamically). Anyway you should have not too much concern in it.
Although it's still hard and non-trivial task to tie classes hierarchy with such a discrete way of execution of a typical PHP application. Once wise man have said once, "If Windows were have to restart after each user's click, it were written completely different".
welcome to SO.
I am by no means a PHP expert, here is my thought comes on top of my head:
OO programming with PHP does help, but not very likely as the rescue to removing all the redundancies or making your code "neater". The traditional way of coding in PHP can produce nice code. OO helps to encapsulate your code to hide the implementation and reuse others' code by direct composition and/or via inheritance.
I would say the real concern here is how to decouple the "static" html from the "dynamic" PHP.
For instance, there shouldn't be many :
echo "<h1>A title</h1";
echo "<p>blah blah blah...";
Even in conditional printing.
I would say separate the whole business logic on one page/script into several functions, and at least hide the nitty-gritty inside a function.
For your questions on popular OO frameworks of PHP, CakePHP is a good one, got its inspiration from Ruby on Rails.
Read MVC Tutorial in PHP to understand what MVC is then start using a MVC Framework like Zend, CakePHP, Symphony or CodeIgniter...
I'm currently starting to write my own CMS in php from ground up using CakePHP (or should i use something else?) for my bachelors degree. And i'm thinking about various stuff that will be needed to do.
One of the things i can not figure out is if i should use a single file (for example, index.php will handle everything, and will include everything) or i should break up my cms into a few smaller files.
so my main questions are
is cakePHP a good choice?
use one file for everything or use multiple files?
do you have any good general advice on building more complex websites using php or any best-practices advice (i don't really understand why they don't teach us this in school)
Using a single entry point or multiple entry points becomes a moot point if you are using most frameworks. CakePHP for instance has an index.php file and all you end up doing is defining models, views, and controllers for different parts of your project. I would imagine that most frameworks these days work this way.
Alternatively, if you choose to roll your own framework and system for managing this, which given this is for a bachelor's degree may be (1) a lot of extra work but (2) more revealing and more instructive, I can speak from experience that I found having a single entry point to be useful.
It enables you to have a common code path for set-up stuff: things like enabling E_STRICT, E_NOTICE, etc. for debugging and reliability purposes. Things like sanitizing form inputs to work around the magic-quotes setting. Yes you can do that from an include 'globals.php' but:
Putting everything in one place also lets you come up with a standard file-naming convention and an __autoload handler that will help remove any include or require directives except for perhaps one. Means you can add classes and such without having to also remember to update a master file.
And this is entirely subjective, but I have found that it's easier to create simpler URLs using this. Instead of /volunteers/communities.php?id=Hedrick_Summit I can do /volunteers/communities/Hedrick_Summit which is more pleasing to me.
As for the choice of CakePHP, I have briefly toyed around with that framework. What I don't like about frameworks in general is they often have to be too general, to the point it results in extra cruft and slower page rendering. And the moment you have to do something that pushes the boundaries of the framework, and you will, you end up fighting the framework.
But to be fair, CakePHP seems to be adequate and generally well-designed. I personally took issue with the ORM layer but that was me striving for perfection and actually trying to do work in the SQL query. It has a reputation for being slow, but unless you're trying to build the next Facebook you should be fine.
Using a single file "entry point" gives you more flexibility when it comes to routing requests to various logic - you'll only ever have to worry about filtering one spot in a request chain.
These are really subjective questions.
I, once, wrote a CMS in php from ground up for my 3rd year project.
What I did was basically:
Checking how other people did it (Plume CMS and CMSmadesimple were a good start)
I didn't use any framework (that was a requirement)
and Yes, I used index.php with multiple params to handle different pages.
Answer is yes use multiple files in multiple directories, it makes all difference in the world when you need to debug or scale.
I would advise you to keep in mind the MVC (Model-View-Controller) pattern.
It is one of the most commonly used (and often misused) patterns in the CMS field.
Also, don't be afraid about looking what other people are doing. Read the code from Joomla, Drupal and other open source CMS. Have a look to language different from PHP to have a comprehensive glance about the possibilities.
Don't try to simply re-invent the wheel. Even if this is simply a Uni assignment, try to put something new on your CMS. Something that would push me to use yours instead of other CMS.
is cakePHP a good choice?
That's a highly subjective question and as such unanswerable. Though, if you want to experiment with architecture (eg. compare front controllers to page controllers), you probably should build more from scratch, as a lot of those decisions have already been made by the writers of said framework (And a lot of other frameworks, for the matter).
use one file for everything or use multiple files?
It's called a front controller (single entrypoint) or page controllers (multiple entry points). Get a copy of Patterns of Enterprise Application Architecture by M. Fowler.
do you have any good general advice on building more complex websites using php or any best-practices advice (i don't really understand why they don't teach us this in school)
There are billions of CMS's. Find some of them and analyse them to find out what they did and how they differ from each other. Trying to categorise the different approaches and compare their strenghts/weaknesses could make for a good paper.
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.
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.
I want to create a 100% object oriented framework in PHP with no procedural programming at all, and where everything is an object. Much like Java except it will be done in PHP.
Any pointers at what features this thing should have, should it use any of the existing design patterns such as MVC? How creating objects for every table in the database would be possible, and how displaying of HTML templates etc would be done?
Please don't link to an existing framework because I want to do this on my own mainly as a learning excercise. You will be downvoted for linking to an existing framework as your answer and saying 'this does what you want'.
Some features I'd like to have are:
Very easy CRUD page generation
AJAX based pagination
Ajax based form validation if possible, or very easy form validation
Sortable tables
Ability to edit HTML templates using PHP
I've gone through many of problems on your list, so let me spec out how I handle it. I am also OOP addict and find object techniques extremely flexible and powerful yet elegant (if done correctly).
MVC - yes, hands down, MVC is a standard for web applications. It is well documented and understandable model. Furthermore, it does on application level what OOP does on class level, that is, it keeps things separated. Nice addition to MVC is Intercepting Filter pattern. It helps to attach filters for pre- and post-processing request and response. Common use is logging requests, benchmarking, access checking, caching, etc.
OOP representation of database tables/rows is also possible. I use DAO or ActiveRecord on daily basis. Another approach to ORM issues is Row Data Gateway and Table Data Gateway. Here's example implementation of TDG utilising ArrayAccess interface.
HTML templates also can be represented as objects. I use View objects in conjunction with Smarty template engine. I find this technique EXTREMELY flexible, quick, and easy to use. Object representing view should implement __set method so every property gets propagated into Smarty template. Additionally __toString method should be implemented to support views nesting. See example:
$s = new View();
$s->template = 'view/status-bar.tpl';
$s->username = "John Doe";
$page = new View();
$page->template = 'view/page.tpl';
$page->statusBar = $s;
echo $page;
Contents of view/status-bar.tpl:
<div id="status-bar"> Hello {$username} </div>
Contents of view/page.tpl:
<html>
<head>....</head>
<body>
<ul id="main-menu">.....</ul>
{$statusBar}
... rest of the page ...
</body>
</html>
This way you only need to echo $page and inner view (status bar) will be automatically transformed into HTML. Look at complete implementation here. By the way, using one of Intercepting Filters you can wrap the returned view with HTML footer and header, so you don't have to worry about returning complete page from your controller.
The question of whether to use Ajax or not should not be important at time of design. The framework should be flexible enough to support Ajax natively.
Form validation is definitely the thing that could be done in OO manner. Build complex validator object using Composite pattern. Composite validator should iterate through form fields and assigned simple validators and give you Yes/No answer. It also should return error messages so you can update the form (via Ajax or page reload).
Another handy element is automatic translation class for changing data in db to be suitable for user interface. For example, if you have INT(1) field in db representing boolean state and use checkbox in HTML that results in empty string or "on" in _POST or _GET array you cannot just assign one into another. Having translation service that alters the data to be suitable for View or for db is a clean way of sanitizing data. Also, complexity of translation class does not litter your controller code even during very complex transformations (like the one converting Wiki syntax into HTML).
Also i18n problems can be solved using object oriented techniques. I like using __ function (double underscore) to get localised messages. The function instead of performing a lookup and returning message gives me a Proxy object and pre-registers message for later lookup. Once Proxy object is pushed into View AND View is being converted into HTML, i18n backend does look up for all pre-registered messages. This way only one query is run that returns all requested messages.
Access controll issues can be addressed using Business Delegate pattern. I described it in my other Stackoverflow answer.
Finally, if you would like to play with existing code that is fully object oriented, take look at Tigermouse framework. There are some UML diagrams on the page that may help you understand how things work. Please feel free to take over further development of this project, as I have no more time to work on it.
Have a nice hacking!
Now at the risk of being downvoted, whilst at the same time being someone who is developing their own framework, I feel compelled to tell you to at least get some experience using existing frameworks. It doesn't have to be a vast amount of experience maybe do some beginner tutorials for each of the popular ones.
Considering the amount of time it takes to build a good framework, taking the time to look into what you like and loathe about existing solutions will pale in comparison. You don't even need to just look at php frameworks. Rails, Django etc are all popular for a reason.
Building a framework is rewarding, but you need a clear plan and understanding of the task at hand, which is where research comes in.
Some answers to your questions:
Yes, it should probably use MVC as the model view controller paradigm translates well into the world of web applications.
For creating models from records in tables in your database, look into ORM's and the Active Record pattern. Existing implementations to research that I know of include Doctrine, more can be found by searching on here.
For anything AJAX related I suggest using jQuery as a starting point as it makes AJAX very easy to get up and running.
Creating your own framework is a good way to gain an appreciation for some of the things that might be going on under the hood of other frameworks. If you're a perfectionist like me, it gives you a good excuse to agonize over every little detail (e.g. is should that object be called X or Y, should I use a static method or an instance method for this).
I wrote my own (almost completely OO framework a while ago), so here's my advice:
If you've worked with other frameworks before, consider what you liked/didn't like and make sure yours gives you exactly what you want.
I personally love the MVC pattern, I wouldn't dream of doing a project without it. If you like MVC, do it, if you don't don't bother.
If you want to do JavaScript/AJAX stuff, do use a JavaScript library. Coding all your own JavaScript from scratch teaches you a bit about the DOM and JavaScript in general, but ultimately its a waste of time, focus on making your app/framework better instead.
If you don't want to adopt another framework wholesale, take a look at whether there are other open source components you like and might want to use, such as Propel, Smarty, ADOdb, or PEAR components. Writing your own framework doesn't necessarily mean writing everything from scratch.
Use design patterns where they make sense (e.g. singletons for database access perhaps), but don't obsess over them. Ultimately do whatever you think produces the neatest code.
Lastly, I learned a lot by delving into a bit of Ruby on Rails philosophy, You may never use RoR (I didn't), but some of the concepts (especially Convention over Configuration) really resonated with me and really influenced my thinking.
Ultimately, unless your needs are special most people will be more productive if they adopt an existing framework. But reinventing the wheel does teach you more about wheels.
At the risk of sounding glib, this seems to me like any other software project, in this sense:
You need to define your requirements clearly, including motivation and priorities:
WHY do this? What are the key benefits you hope to realize? If the answer is "speed" you might do one thing, if it's "ease of coding" you might do another, if it's "learning experience" you might do a thid
what are the main problems you're trying to solve? And which are most important? Security? Easy UI generation? Scalability?
The answer to "what features it should have" really depends on answers to questions like those above.
Here are my suggestions:
Stop what you're doing.
It's already been done to death.
Click this Zend Framework or that CakePHP or maybe even this Recess Framework.
Now, my reasons:
... if you've worked with developers at all, you've worked with developers that love reinventing the wheel for no good reason. This is a very, very common failure pattern.
... they would go off and write hundreds and thousands of the crappiest languages you could possibly imagine ...
... "Oh, I'm gonna create my own framework, create my own everything," and it's all gonna be crappier than stuff you could just go out and get ...
from StackOverflow Podcast # 3.
So, save yourself some time, and work on something that solves a problem for people like a web app that lets people automatically update Twitter when their cat's litter box needs cleaning. The problem of "Object Oriented PHP Framework" is done. Whatever framework you slap together will never be as reliable or useful or feature rich as any of the freely available, fully supported frameworks available TODAY.
This doesn't mean you can't have a learning experience, but why do it in the dark, creating a framework that will grow into a useless blob of code, leaving you without anything to show for your time? Develop a web app, something for people to use and enjoy, I think you'll find the experience incredibly rewarding and EDUCATIONAL.
Like Jim OHalloran said, writing your own framework gives you a very good insight into how other frameworks do things.
That said, I've written a data-access layer before that almost completely abstracted away any SQL. Application code could request the relevant object and the abstraction layer did lots of magic to fetch the data only when it was needed, didn't needlessly re-fetch, saved only when it was changed, and supported putting some objects on different databases. It also supported replicated databases, and respected replication lag, and had an intelligent collection object. It was also highly extensible: the core was parameter driven and I could add a whole new object with about 15 lines of code - and got all the magic for free.
I've also written a CRUD layout engine which was used for a considerable percentage of a site. The core was parameter driven so it could run list and edit pages for anything, once you wrote a parameter list. It automatically did pagination, save-new-delete support etc etc, leveraging the object layer above. It wasn't object-oriented in and of itself, but it could have been made so.
In other words, a object-oriented framework in PHP is not only possible, it can be very efficient. This was all in PHP 4, BTW, and I bumped up against what was possible with PHP 4 objects a couple of times. :-)
I never got as far as a central dispatch that called objects, but I wasn't far away. I've worked with several frameworks that do that, though, and the file layout can get hairy quickly. For that reason, I would go for a dispatch system that is only as complex as it needs to be and no more. A simple action/view (which is almost MVC anyway) should get you more than far enough.
I initially started creating my own framework with similar ideals to your own. However, after a couple of months I realised I was re-creating work that had been done many times over. In the end I found an open source framework which was easily extendable and used it as a basis for my own development.
The features I implemented myself:
MVC Architecture
Authentication object
Database access class
URL rewriting config
Pagination class
Email class
Encryption
The features I looked at and thought, forget it! I'll build on top of someone elses:
Caching class
Form validation class
FTP class
Plugin-ability classes
Of course, writing a framework that outperforms the open source options is possible, but why would you bother?
It's true that some developers reinvent the wheel for no good reason. But because there are already good frameworks around doesn't mean that it's a waste of time doing one yourself. I started on one a while ago with no intention of using it for anything more than an exercise. I highly recommend doing it.
I've got the perfect link for you my friend: http://nettuts.com/tutorials/php/creating-a-php5-framework-part-1/. This is an awesome tutorial I have looked at, and its not too overwhelming. Plus look around the PHP section of that site I saw an article on CRUD. As for the AJAX look elsewhere, but you have to start somewhere, and this tutorial is awesome.
Note: this tutorial has 3 parts and I think it brings up MVC in the second instalment, but starts the first part using other methods.
The one, huge selling point I would look for in a new framework is that it would make writing testable code easy.
We typically work with Zend Framework, and it's mostly awesome, but trying to unit test/test drive ZF-based code is not far short of masochism.
If you could provide a framework that replaces the MVC parts of ZF with something that allows us to write testable code, whilst still allowing us to use the library parts of ZF, I will - quite literally - buy you a beer.
I'll buy you two beers if you ditch the AJAX. There's a huge gulf between an OO PHP framework and a JavaScript framework.
Please don't link to an existing framework
I will not, I started writing my own for learning purposes, and took a peek into some of the mainstream frameworks, and even with my limited knowledge see so many mistakes and bad ideas in them.
They're built by hardcore developers, not end users.
I'm in no way saying I could write better than the "big boys" but I (along with most of you I imagine) could point out why some things they do are bad, even if just because they're not end user/non-developer friendly...
I wonder how your framework is doing, some 6 years on?
Are you still working on it? Did you stop?
Should You Write Your Own Framework
This is probably a little late for you, but for anyone else, writing your own framework is a fantastic thing to do for learning purposes.
If, however, you are wanting to write one other than learning purposes, because you cannot work out the one you are using, or because it's too bloated, then do not!
Believe me, and don't be insulted, you would not be here contemplating it if you are a knowledgeable enough developer to do so successfully!
Last year I wanted to learn OOP/classes, and more advanced PHP.
And writing my own framework was the best thing I did (am actually still doing), as I have learned so much more than I anticipated.
Along the way I've learned (to name a few):
OOP/Classes many best practices which come with it - such as
Dependency Injection, SRP
Design patterns, which help you write code and structure your system
in such a way that it makes many things logical and easy. For an
example see Wiki - SOLID
Namespaces
PHP Error Handling and all of the functionality which that provides
A more robust (and better) understanding of MVC, and how to apply it
appropriately (as there is no clear cut way to use it, just guides
and best practices).
Autoloading (of classes for OOP)
Better code writing style and more structured layout, and better
commenting skills
Naming conventions (it's fun making your own, even if based on
common practices).
And many other basic PHP things which you invariably come across accidentally from reading something.
All of this not only vastly improved my grasp of PHP and things which come with it, to a more advanced level, but also some of the commercially/widely used methods and principles.
And this all boosted my confidence in using PHP in general, which in turns makes it easier to learn.
Why Write a Framework To Learn All of This
When you start out, you learn the basics - A (variables), then B (how to write a basic function), etc.
But it doesn't take long when you're trying to learn more advanced things, that to learn and use D and E, you also have to learn and understand F, G, H, and J, and to know those you have to know K, L, and M, and to know parts of L and M you first need to understand N and O...
It becomes a minefield as trying to learn one thing brings the need to first learn a few other things, and those other things often bring a need to understand various other things.
And you end up a mile away from where you started, your mind tingling and shooting sparks from it, and about 20 tabs open all with various advanced PHP things, none of which you are 100% comfortable with.
But over time, with practice and most certainly dedication, it will all fit into place, and you'll look back at code, even a collection of files/classes, and think "Did I write that.."?
Writing a framework helped greatly with this "minefield" because:
I had specific tasks to do, which brought about the need to learn and
implement other things, but specific things. This allowed me to focus
on less things at once, and even when something branches off to
various other things, you can reel it back in to where you started
because you are working on something specific. You can do this with
any learning, but if you do not have some goal, or specific task you
are focusing on, you can easily get distracted and lost in the ether
of things to learn.
I had something practical to work with. Often reading tutorials about
an animal class, and how cat and dog classes extend animal etc,
can be confusing. When you have a real life task in your own
framework, such as how do I manage XYZ, then you can learn how
classes work easier because you have trial and error and a solid
requirement which you understand, because you created the
requirement! Not just theory-like reading which means nothing
usually.
I could put it down when my mind was blown, although as it was my
framework (my Frankenstein's monster in the beginning :P) I wanted to
press on, because it was interesting, and a personal goal to learn
and sort the next stage, to resolve an issue I was stuck with, etc.
You can do it how you want. It might not be best practice, but as long as you are trying to learn best practice, over time you will improve, and likely easier than just reading tutorials, because you are in control of what and how you do something.
Wait, I Shouldn't Re-invent the Wheel Though
Well, firstly, you cannot reinvent the wheel, it is impossible, as you will just make a wheel.
When people say "Don't reinvent the wheel", they of course mean "there are already frameworks out there", and to be fair, they are written by skilled developers.
That's not to say the frameworks don't have problems or issues, but in general they are pretty solid, secure and well written.
But the statement is nonsensical in relation to writing your own framework!
Writing your own framework for learning purposes is really useful.
Even if you plan to use it commercially, or for your own website, you haven't just "re-invented the wheel", you've made something else.
Your framework won't be like the others, it won't have many features and functionality, which might be a major advantage to you!
As long as you understand about best security practices etc, because you can think you are writing a great system, which is super fast and without all the bloat other frameworks have, but in fact you have holes in places which someone could crawl into...
But a project for learning which you don't use on the internet is ideal - or use it, eventually, when you are advanced enough to know it's secure!
With all that said, you should write your own framework IF:
You are not needing it any time soon! It takes a lot of time as
there are so many aspects to consider, learn, and trial and error
leads to refactoring (a lot at first!)
You are willing to read, code, test, change, read, code, and read
some more. There is a lot of good advice on the internet for advanced
PHP, most of it mind blowing at first, like reading all the design
patterns. But they eventually make sense, and end up helping you
resolve problems you face, and how to do things within your
framework.
Willing to put the time in, and keep trying to improve, and head
towards best practice, especially with security. Speed issues shouldn't be an issue with a small framework, and besides, if you have a fairly decent system, you can usually refactor and make speed improvements. usually if you have significant speed issues it means you've chosen intensive operations, which can usually be addressed by doing it a different way.
.
Without previous experience, or an advanced knowledge of PHP, you will likely spend some time writing a framework, further reading and knowledge will show you that your approach is skewed, and so you might delete everything and start again.
Don't be disheartened by this.
I did exactly that, as I learned so much advanced patterns and ways of doing things along the way in the first month, I ended up where refactoring was no good, and a blank canvas with a whole new approach was the only option.
However, this was quite pleasing, as I saw a much better structure take form, and I could see not only a better framework foundation start to take place, but realised it was because I had a better understanding of advanced PHP.
Just do it! Just make sure you have a plan of what you want it to do before you even write some code.
Seriously, write down on paper how you are going to load error checking, are you going to have auto loading, or include files when needed? Are you going to have a centralised loading mechanism, which instantiates classes when you need them, or some other method?
Whatever you do, and whatever stage you are at, if you are heading into new territory, plan it first. You'll be glad of it when you hit a brick wall, can go back to your plans, and realise a slight deviation to your plans will resolve it.
Otherwise you just end up with a mess and no plan or way to re-deign it to resolve the current problem or requirement you face.
You are looking to build exactly same thing I've worked on for a few years and the result is Agile Toolkit.
Very easy CRUD page generation
$page->add('CRUD')->setModel('User');
AJAX based pagination
All pagination and many other things are implemented through a native support for AJAX and Object Reloading. Below code shows a themed button with random label. Button is reloaded if clicked showing new number.
$b=$page->add('Button')->setLabel(rand(1,50));
$b->js('click')->reload();
Ajax based form validation if possible, or very easy form validation
All form validations is AJAX based. Response from server is a JavaScript chain which instructs browser to either highlight and display error message or to redirect to a next page or perform any other javascript action.
Sortable tables
Table sorting and pagination has a very intuitive and simple implementation when you can really on object reloading.
Ability to edit HTML templates using PHP
This seems out of place and a wrong thing to do. Templates are better of in the VCS.