PHP Oop Core Framework

Fully Object Oriented framework in 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!

simple explanation PHP OOP vs Procedural?

Background: You asked for a "simple explanation" which suggests:

  1. You want a no-nonsense overview without jargon
  2. You want something that will help you learn from the beginning
  3. You have discovered that no two people ever answer the question the same way, and it's confusing. That's the reason you are here asking for a simple explanation. Yes?

Short No-Jargon Answer:

  1. Many introductory explanations jump quickly into "OOP real world" examples. Those can tend to confuse more than help, so feel free to ignore that for now.
  2. You can think of source code simply as "chunks" of functionality, that just happen to be saved to individual files.
  3. There are different ways of organizing those "chunks"; depending on things like conventions of the programming language, the background and training of the developer(s), or just plain old personal preference.
  4. OOP and Procedural programming are simply two main, generally-recognized methodologies, for how to organize and arrange those "chunks" of code.

Long No-Jargon Answer:

Procedural vs OOP is just one aspect of a fundamental issue of computer programming: how to make your code easy to understand and a piece of cake to professionally maintain. You can actually write "Procedural" code that follows some of the principles of OOP, so the two are not necessarily opposites.

Your understanding will really grow once you learn other object-oriented programming languages, among which, PHP is a "new kid on the block".

Here is a quick overview of what you will learn as you build experience:

  • You can write PHP source code that does useful tasks

  • You can organize useful tasks into "chunks" of code

  • You can think of "chunks" of code independently of the individual files where they are saved

  • Sometimes those "chunks" of code will behave differently based on parameters you pass in

  • Chunks of code that accept parameters are called "Functions"

  • Functions can be "chunked" together, and there are different ways of doing this:

    • For example: you could have just one big PHP file with all the functions you have ever written in your entire life, listed in alphabetical order by function name
    • For example: you could have multiple PHP files with functions that are chunked together by subject matter [e.g., functions for doing basic string manipulation, functions for processing arrays, functions for file input/output, etc]
  • OOP is a special way of "chunking" Functions together into a "Class"

  • A Class is just another level of "chunking" code together so that you can treat it as a unified whole

  • A Class can be thought of as a "chunking" of methods and properties

    • methods are simply functions that are logically related to one another in some meaningful way. The words "method" and "function" are basically two different terms for the same thing.
    • properties are simply data values that are related to the class. These are values that are intentionally non-isolated to any individual function, because more than one of the functions in the class should have access to them.
      • For example: if your class has a bunch of methods for doing astronomy, properties of the class might be the values for certain famous numbers that all astronomy methods need to know about (like Pi, the speed of light, the distance between specific planets, etc.).
    • This is where most OOP explanations get confusing because they branch off into "real world examples" which can quickly get off-topic. Often, "real world" is a euphemism for the ontological perspectives of a particular individual or group. That tends to be useful only once you already understand the concept well enough to teach it to someone else.
    • To understand OOP without confusion, you can skip the "real world" examples for now, and just focus on the code. A Class is simply a way to store functions (aka methods) and properties (aka data) as PHP code in one or more related "chunks" where each individual "chunk" deals with a specific topic or piece of functionality. That's all you need to know in order to get started.
  • A Class is useful because it allows you to organize your code at a very high level in a way that makes it easy for you to understand, use, and maintain.

  • When someone has written a lot of functions, and organized them into a lot of Classes, and gotten those to work together in some cool way, they package the whole thing together and call it a "Framework".

  • A Framework is just the next-highest level of "chunking" (including coding style and conventions) that one or more people agree on because they like the way the code is organized and it suits their working style, preferences, values, plans for world domination, etc.

See also

  • OOP appeal

is PHP itself transforming into a framework or big library?

PHP has always been a "framework" for building websites, in the sense that it has specific support for handling web pages and sessions. [Show me any serious application coded in PHP that isn't fundamentally a web site]. IMHO, as a programming langauge, it has little to recommend it, even with the afterthought addition of OO; the only thing that saves PHP is the web support (including the huge library of functions), and the fact that it is free.

As one example of how poorly it carries itself as a langauge, the PHP folks are having trouble with Unicode. The hints about Unicode were loud and clear back in the middle 90s, and every modern langauge since them simply insisted on having direct Unicode support in the language. Hint: PHP wasn't designed; it simply grew.

Should I begin learning PHP Framework?

OOP is a methodology used to organise your code into meaningful, reusable entities and it doesn't alone answer to the question of "how to best organize your code to create web applications".

Most of the web frameworks use Model-View-Controller architecture (MVC) along with OOP. In order to understand how web frameworks work, I suggest you to familiarize yourself with MVC as well (for a starting point, see "Coding Horror: Understanding Model-View-Controller")

Also, regardless of any frameworks, it is crucial to understand some basic concepts when creating web applications. At the minimum, familiarize yourself with how sessions work (http://www.php.net/manual/en/book.session.php), as well as how you can access databases (PDO for generic database connectivity, MySQL for MySQL-specific binding, etc.).

As for what web framework to choose, the options are plenty. Therefore consider the following pointers as informative:

  • Yii Framework has a pretty clean OOP-based design (http://www.yiiframework.com/)
  • Another popular object-oriented PHP framework is CakePHP (http://cakephp.org/)
  • For a more light-weight framework with less overhead, consider CodeIgniter (http://codeigniter.com/)
  • The de facto web framework for PHP is Zend (http://framework.zend.com/). Its huge, comprehensive, well-supported, but not always the perfect companion when travelling light.
  • Also note that if you organize your code according to MVC, you may find yourself most comfortable when not using any frameworks at all

Also note that unlike in Java, in PHP object-oriented features have been slowly added during its versions 4 and 5. Therefore, many web frameworks designed for earlier versions of PHP may not provide you as cleanly object-oriented design as you might want. Therefore when choosing a framework, consider whether you opt-in for backward-compatibility (PHP4 support) or are you seeking for a clean, object-oriented design in the framework (mostly PHP5 required).

Do you need a good background in OOP before moving to frameworks?

Its always good to have a strong understanding of what you are working on. so yes I think to be a good programmer you should learn at a high level how OOP works so you understand how classes can be extended etc.

At some point though you will know enough to get started with your framework. So once you are a few chapters in, start using the framework of choice and any time you see something you don't understand research it and repeat.

EDIT: to answer you updated question about procedural.

You should understand PHP first and foremost, OO is very useful but don't blindly create OO code. Understand why you are doing it and know when you don't need to use it. For example (most programers don't really run into this problem) when you hit large scale you may need to push back on some of your OO code to make it run faster. OO is an overhead but its a very useful overhead.

Is PHP 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).

There are still a lot of loose functions however, so there might be a disagreement about how object oriented PHP is. I think it is. And yes CakePHP is an object oriented framework.

Working on a PHP framework with an MVC pattern ( New to OOP programming ) Having issues

From this line:

$this->$model = new $model;

It appears your passing in a string and using it both as the property name and the class name. Perhaps you're passing in a name that is not exactly main_model. Though variable/property names are case-sensitive, class names are not. So, they're may be a case mismatch. Pass $this through get_object_vars to see what properties are available. Keep in mind that dynamically adding properties in this way will make them public.

These lines should be examined as well:

$this->_view = $view;

$this->_view = new view;

You're overwriting the property. I'm sure this is unintentional and may be part of the problem you're experiencing. Perhaps you're trying to use the same approach as you did with the controller (store name, use for instantiation and access).



Related Topics



Leave a reply



Submit