Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fully Object Oriented framework in PHP

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
like image 860
Ali Avatar asked Feb 11 '09 04:02

Ali


People also ask

Is PHP fully object-oriented?

Yes, the latest versions of PHP are object oriented. That is, you can write classes yourself, use inheritance, and where appropriate, the built in functionality is built in objects too (like MySQL features).

What is object-oriented programming PHP?

PHP What is OOP? OOP stands for Object-Oriented Programming. Procedural programming is about writing procedures or functions that perform operations on the data, while object-oriented programming is about creating objects that contain both data and functions.

Is Ruby 100% object-oriented?

Ruby is a pure object-oriented language and everything appears to Ruby as an object. Every value in Ruby is an object, even the most primitive things: strings, numbers and even true and false. Even a class itself is an object that is an instance of the Class class.


6 Answers

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!

like image 149
Michał Niedźwiedzki Avatar answered Oct 17 '22 17:10

Michał Niedźwiedzki


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.
like image 41
navitronic Avatar answered Oct 17 '22 18:10

navitronic


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.

like image 24
Jim OHalloran Avatar answered Oct 17 '22 19:10

Jim OHalloran


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.

like image 32
Steve Lane Avatar answered Oct 17 '22 19:10

Steve Lane


Here are my suggestions:

  1. Stop what you're doing.
  2. It's already been done to death.
  3. 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 image 21
Jake McGraw Avatar answered Oct 17 '22 19:10

Jake McGraw


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.

like image 40
staticsan Avatar answered Oct 17 '22 18:10

staticsan