OOP PHP Confusion, transition from procedural to OO PHP

I am still new to PHP and am trying to learn it. The big difficulty that I am facing is that I just can’t tilt my head to think about how the PHP site is structured using classes, objects, namespaces.

I'm not completely new to OOP, as I have little experience with Python and Java, but PHP OOP only alerted me. Many of the PHP beginner books I wrote were in procedural PHP. I followed them, made a 1-2-2 small site, but when I got to OOP, I was just stuck, and all the tips on how you made the transition from procedural to OO PHP would be appreciated. In particular, these are my questions at this moment.

  • What are the types of classes that are usually created? I was thinking of giving a class for each table in my database (User, Book), and also, possibly, in the form class, are there any other type of candidates that can also be turned into classes?
  • Any other way to reduce duplication of HTML code besides the old plain require () and include ()?
  • Any recommended ways to structure a typical PHP website? Currently, I only know that the folder has a file. But I would like to know more.

Thanks.

+4
source share
6 answers

You have questions, here are my answers!

  • Classes that you create in PHP can be associated with objects such as "User", "Book", as in a permanent program. If you look at a framework such as Code Igniter , you can create a class specific for building database queries for a class that uses an MVC architecture consisting of several classes to display your entire site.

  • To reduce code duplication, you can, for example, write a class to build the table (or if you really like the creator of the table div). Then you can write methods such as makeRow (), makeDivision (), etc ... get really fancy, and then you can write pure PHP code that can generate really big powerful pages.

    EDIT :
    If you were talking about reducing the number of inclusions that you would need to make for classes, then yes, “Class autoload” on the PHP website is what you want to see!

  • The structure of your site may be based on the model you want to use. Now it seems that MVC models are popular within frameworks, but it is up to you how you want your web application to be created. I am sure that you can take any architecture model and build your site around it.

    With all that said, if you don’t feel that you are starting with an absolute scratch in your project, there are many PHP frameworks on your computer:
    Comparison of web application frameworks: PHP via Wikipedia

+3
source

A very interesting question that brings us back to the centuries-old discussions on procedural and OO programming. Why choose one or the other? Answer: he has one. The whole purpose of software development is to do something. No matter how you get there? Depends. If you get there very carelessly and require a lot of updates, this is a big waste of time. Does it program? Absolutely not.

It seems your real question is how to integrate OO into the website. This is really not what you should do for this. What are you trying to achieve with this website? It contains many different states of an application with user interaction in FSM or it is just a bunch of static pages. How much information does these pages share?

First consider your specific questions:

  • What types of classes are usually created? Whatever class he wants! Before entering a single character code, you must sit down and write a project for your application. No one can tell you how to do this: write some documentation, pseudo-code (even in php, if you want), draw up a UML diagram, etc. Find out how your application can be shared. Do not make object division errors based on their logical separation in the real world (User, Book), if that makes no sense. Why do you need a book object? How does it interact with the user?

You can create a very simple class to display a standard web page:

class anypage { public function header() { return '<head></head>'; } public function footer() { return '<br />Copyright &copy; ' . date('Y'); } public function render($body) { return '<html>' . $this->header() . "<body>$body{$this->footer()}</body></html>"; } } 

Then to any page call:

 $page = anypage; echo $page->render("My Page Content"); 

In any case, I'm talking about the general principles of OO than about PHP, but this is a question that cannot be answered. You develop the classes that your application requires to do the job. A good example of using an object in PHP is PHPTAL , a template language. Your web page might look like this:

 $page = new PHPTAL('mytemplate.xhtml'); echo $page->execute(); 

The PHPTAL class takes care of creating html from a template file. This is an example of which object you can use for.

Of course, PHPTAL is huge, and it is divided into many compartments. Looking at the source code, we see the classes Attr, Element, Node .. all these are fragments of an XML document, and they have a class representing them.

An important part of OOP is that objects work together. Each object should serve a purpose and do what is good. I do not like objects that are models for nouns, such as "User" or "Book", if they do nothing. PHPTAL does a great job of presenting a view for your page, but how do you know which page to display? You can use an object to handle this:

 class controller { public function __call($_, $_) { return $this->hello(); } public function hello() { session_start(); $view = new PHPTAL('hello.xhtml'); return $view->execute(); } public function goodbye() { session_destroy(); $_SESSION = array(); $view = new PHPTAL('goodbye.xhtml'); return $view->execute(); } } 

On the main page you would:

 $c = new controller; echo $c->$_REQUEST['action'](); 

If the "action" is set by the request, the controller responds accordingly, calling this action. hello used by default thanks to magic __call() .

Like other OO languages ​​you are familiar with, you can even have events in PHP:

 class controller { private $models = array(); private $_listeners = array(); public function __construct() { $model = new model; $this->models[] = $model; $this->_listeners[] = $model; } public function action($action = 'hello', $events = array()) { $this->$action(); foreach ($events as $type => $data) { foreach ($this->_listeners as $listener) { $event = "fire_" . $type; $listener->$event($data); } } } } class model { public function fire_hello($name) { echo 'hello ' . $name; } } 

Like the other answers, a good start is to take a look at the PHP framework. I recommend Kohana , as it is a good OO structure. I do not necessarily suggest you create a website, but look at the documentation and code to better understand the development of OO for PHP.

2 PHPTAL or another template engine is a great way to reduce html duplication. An example is even my miniature class anypage . You do not have to have an html file, and then use require() include() or virtual() to pass it into your code for reuse. Instead, you can have a wrapper that stores and creates a common html template. I cannot stress enough how much I love PHPTAL for this purpose. XSLT is an alternative.

3 There is no way to do this. Others suggest using the framework. I do not necessarily disagree. Using the framework helps a lot in taking care of some unpleasant things to do with customization. This is not a magical problem solving a placebo, but it is good for some things. If you are just trying to learn and there are no limits in time, I say, I am writing your own framework. This will definitely teach you how to program OO in PHP. If time is a concern, use one of the 500,000 frameworks that others offer. Regarding the structure of your website, I usually have a _js folder for javascript and a _stylesheets folder for stylesheets. All the php and xhtml template files that I use are simply placed in the folders that they belong to logically. This is not rocket science, this is software development!

+2
source

The MVC pattern is essentially a de facto pattern for web applications, regardless of language. Several structures use this template, including the Zend Framework, CodeIgniter, and Kohana.

Like everyone else, __autoload () or spl_autoload_register () is the way to go when it comes to eliminating the need to follow, includes / requires.

Remember that the currency of OOP objects . You don’t get much if you just flip some data in the OO model and call it day. I suggest you take a look at Matt Zandstra's PHP 5 book, Objects, Templates, and Practice, as well as a Set of Four Design Patterns: Elements of Reusable Object-Oriented Software, to really see how to use objects throughout the project.

+1
source

You may find that working within the framework means that you are only creating some components yourself and that there are many examples of best practice.

I moved from procedural material to the Zend Framework , which is an excellent structure and includes a complete MVC model that helps to clearly define what your different objects should do and how they all fit together.

It will probably be a little learning curve, but after a while it makes a lot more sense than the procedural material!

0
source

Use an object-oriented MVC framework such as CodeIgniter (which is very simple), Yii (a bit more complicated) or CakePHP or Symfony (much more complicated). You can see how different objects are related to each other, and the benefits of using them.

A good example of classes is the interaction between "form", "validation", and "schema." You can instantiate a form by passing it a diagram, and then use the methods in the “form” to generate HTML without repeating it over and over. When the user submits the form, you validate each field using an instance of the Validation class, and then write it to the database using the Model. Each table in your database has a “Model” that defines how data is written and retrieved from the database (CRUD).

You can avoid using a lot of queries and use "__autoload ()".

0
source
  • It depends on what you want to achieve. In a relatively sophisticated web application, you can follow a typical MVC approach . In this scenario, you can create at least two classes: one for the model and one for the controller. And then you have several templates (simple PHP files), the contents of which are filled / completed by the controller. You can create more classes (forms, utilities, code generators, ..) as needed, but be careful that your code is compact and easy to maintain.

  • Many frameworks rely on the __autoload() magic method. Another alternative is to create your mechanism for processing all this material, possibly using the AutoLoader class.

  • Use the framework. Jokes aside. Or at least take the framework as an example. I recommend CakePHP or CodeIgniter because of their simplicity of file structure.

0
source

All Articles