Php: Real World Oop Example

PHP: Real world OOP example

OOP is not only about how a single class looks and operates. It's also about how instances of one or more classes work together.

That's why you see so many examples based on "Cars" and "People" because they actually do a really good job of illustrating this principle.

In my opinion, the most important lessons in OOP are encapsulation and polymorphism.

Encapsulation: Coupling data and the logic which acts on that data together in a concise, logical manner
Polymorphism: The ability for one object to look-like and/or behave-like another.

A good real-world example of this would be something like a directory iterator. Where is this directory? Maybe it's a local folder, maybe it's remote like an FTP server. Who knows!

Here's a basic class tree that demonstrates encapsulation:

<?php

interface DirectoryIteratorInterface
{
/**
* @return \Traversable|array
*/
public function listDirs();
}

abstract class AbstractDirectoryIterator implements DirectoryIteratorInterface
{
protected $root;

public function __construct($root)
{
$this->root = $root;
}
}

class LocalDirectoryIterator extends AbstractDirectoryIterator
{
public function listDirs()
{
// logic to get the current directory nodes and return them
}
}

class FtpDirectoryIterator extends AbstractDirectoryIterator
{
public function listDirs()
{
// logic to get the current directory nodes and return them
}
}

Each class/object is responsible for its own method of retrieving a directory listing. The data (variables) are coupled to the logic (class functions i.e, methods) that use the data.

But the story is not over - remember how I said OOP is about how instances of classes work together, and not any single class or object?

Ok, so let's do something with this data - print it to the screen? Sure. But how? HTML? Plain-text? RSS? Let's address that.

<?php

interface DirectoryRendererInterface
{
public function render();
}

abstract class AbstractDirectoryRenderer implements DirectoryRendererInterface
{
protected $iterator;

public function __construct(DirectoryIteratorInterface $iterator)
{
$this->iterator = $iterator;
}

public function render()
{
$dirs = $this->iterator->listDirs();
foreach ($dirs as $dir) {
$this->renderDirectory($dir);
}
}

abstract protected function renderDirectory($directory);
}

class PlainTextDirectoryRenderer extends AbstractDirectoryRenderer
{
protected function renderDirectory($directory)
{
echo $directory, "\n";
}
}

class HtmlDirectoryRenderer extends AbstractDirectoryRenderer
{
protected function renderDirectory($directory)
{
echo $directory, "<br>";
}
}

Ok, now we have a couple class trees for traversing and rendering directory lists. How do we use them?

// Print a remote directory as HTML
$data = new HtmlDirectoryRenderer(
new FtpDirectoryIterator('ftp://example.com/path')
);
$data->render();

// Print a local directory a plain text
$data = new PlainTextDirectoryRenderer(
new LocalDirectoryIterator('/home/pbailey')
);
$data->render();

Now, I know what you're thinking, "But Peter, I don't need these big class trees to do this!" but if you think that then you're missing the point, much like I suspect you have been with the "Car" and "People" examples. Don't focus on the minutiae of the example - instead try to understand what's happening here.

We've created two class trees where one (*DirectoryRenderer) uses the other (*DirectoryIterator) in an expected way - this is often referred to as a contract. An instance of *DirectoryRenderer doesn't care which type of instance of *DirectoryIterator it receives, nor do instances of *DirectoryIterator care about how they're being rendered.

Why? Because we've designed them that way. They just plug into each other and work. This is OOP in action.

Real World Examples of Advanced OOP Features for PHP

Not a real world example as such, but one Design Pattern where you usually encounter interfaces and abstract classes is the Command Pattern. See link for example code.

In general, "programming against an interface" is considered good OO practise, because it decouples concrete implementations and let you more easily change them for other implementations, e.g. instead of asking for a specific class

public function fn(ConcreteClass $obj)
{
$obj->doSomething()
}

you just ask that it provides a certain set of methods

public function fn(MyInterface $obj)
{
$obj->doSomething()
}

Interfaces also help teasing apart large inheritance structures. Because PHP supports only Single Inheritance, you'll often see hierarchies like this:

BaseClass -> Logger -> Auth -> User

where each of these contains specific aspects used inside these classes. With an interface, you just do

User implements Loggable, Authenticable

and then include that specific code via Strategy Patterns or Composition/Aggregation, which is ultimately much more maintainable.

For a list of predefined interfaces in PHP see my answer to:

  • where to find "template" interfaces?.

Can you give real world OOP examples in PHP?

Zend framework

Object oriented use of properties/methods in real webapplications?

answering all your questions needs a book as understanding the oop concept completely needs much reading and practicing.
But to answer your post class I give you an easy to use example where you can create a class which will help you create, read, delete and update posts.
This class can be used in all your projects as it's a class and classes are simply there to make our life easier.

So here we go:
first we create the class:

class posts
{
//we just need a post title and a post content for the new post.
//So we create two properties for post_title and post_content
private $post_title; //the variables are private so we we restrict access the them from outside the class.
private $post_content;
private $connection;
//you really don't need here the _constructor function, but it's your choice.
//For example you can do all your database connection stuff in the constructor method to make it easy for users.
//So if someone creates a posts object it is obvious that he's going to make some interactions with the database so you open connections in your constructor.
//next we create the methods for our posts class

public function __constructor()
{
//here you created the connection to your database. You can retrieve
//the parameters to the mysqli_connect from a eg. config.php file to make your class more dynamic.
$this->connection = mysqli_connect('hostname', 'username', 'password', 'databasename');
}

public function create_post($title, $content)
{
$this->post_title=$title;
$this->post_content=$content;
$query="INSERT INTO posttable(id,title,content) VALUES('$this->post_title','$this->post_content')";
$result=$mysqli_query($this->connection,$query);
}

public function update_post($post_id, $post_title, $post_content)
{

}

public function delete_post($post_id)
{

}

public function view_posts($query, $fields)
{
$result=mysqli_query($this->connection, $query);
$finalData=array();
while ($row=mysqli_fetch_assoc($data)) {
foreach ($fields as $field) {
array_push($finalData, $row[$field]);
}
}
return $finalData;
}
}

//now we're going to use the class.
$post=new posts(); //a new posts object is created and the __construct method opened connection to db.
$post->create_post('some title', 'some content');//inserted new post into database.
$post->update_post($id, $content, $title);//you've just updated a post
$post->delete_post($id);//you've just deleted a post.

//getting posts
$query="SELECT * FROM posts";
$fields=array('id','title','content');

$all_posts=$post->view_posts($query, $fields);
//now you have $all_posts which is filled with an array of all posts from the posts table.
//now you can loop through it and show it on your page.
for ($i=0; $i<=count($all_posts); $i++) {
echo '<h1>'.$mydata[$i].'</h1>';
$i++;
echo '<h2>'.$mydata[$i].'</h2>';
$i++;
echo '<h3>'.$mydata[$i].'</h3>';
}

I didn't implement the update and delete method code but I think it's easy for you to write it by yourself.All my goal was to show you how you can use oop in your web applications. I personally have nearly 50 classes written by myself and do all the major jobs for nearly all possible web application tasks. It's up to you how you create your classes. Just for your knowledge, oop programming needs training and experience. You can do a task in multiple forms and with different solutions. You can find dozens of books which teach you oop design who's concept and goal is to teach you how to design a class to the best way.
I hope I was helpful

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

Real world example of OOPS

A comment about OOP: Things like OOP form patterns or ways of structuring code, from the way you've asked the question, it seems you are learning and want to utilise these patterns, this good and I would recommend this kind of thinking (and being conscious of how code is constructed). Recognising these patterns and structures comes with experience in both using and developing for differnt types of frameworks to acheive specific goals. I dont think there is an answer for all your question, as books have been written about this, but continue reading and developing code and these things will become natural.



Related Topics



Leave a reply



Submit