My first php .class

Hi all

Been doing a bit of study regarding php classes and objects over the past couple of nights, bit stressful but very rewarding after I’ve realized the power it can provide, never mind the convenience and how well you can structure your code.

Anyway, Ive created a class for a new html page, just wondering is this a bit over kill and should I be using a class for some like this?

I read somewhere that its wrong to have any html elements in your classes, is this right? Or are there exceptions?

class


class newPage {
    var $Title;
    var $Keywords;
    var $Description;
    var $Content;

function Display( ) {
     echo "<!DOCTYPE html>\
<html lang=\\"en\\">\
<head>\
<meta charset=\\"utf-8\\">\
";
     $this->DisplayTitle( );
     $this->DisplayKeywords( );
     echo "\
<link rel=\\"stylesheet\\" href=\\"css/global.css\\">";
     echo "\
</head>\
<body>\
";
     echo $this->Content;
     echo "\
</body>\
</html>\
";
   }

function DisplayTitle( ) {
     echo "<title>" . $this->Title . "</title>\
";
   }

function DisplayKeywords( ) {
    echo '<meta name="keywords" content="' . $this->Keywords . '">';
    echo '<meta name="description" content="' . $this->Description . '">';
   }

   function SetContent( $Data ) {
     $this->Content = $Data;
   }

}

page view

include "newPage.class.php";

 $Sample = new newPage;

 $Content = "<p>This page was generated by the Page Class example.</p>";

 $Sample->Title = "Using Classes in PHP";
 $Sample->Keywords = "PHP, Classes";
 $Sample->Description = "PHP Classes Rock!";
 $Sample->SetContent( $Content );

 $Sample->Display( );

Any thoughts, good resources or information much appreciated :cool:
And how would you go about adding your pages content inside $Content?

This is a route many people who are new to OOP go down, and it’s a great learning experience. As you get more experience, however, you learn it isn’t a very advantageous approach - but the learning experience is worth going down that route.

First of all, stick to a convention regarding setting variables. The following shouldn’t occur:


$Sample->Title = "Using Classes in PHP";
$Sample->Keywords = "PHP, Classes";
$Sample->Description = "PHP Classes Rock!";
$Sample->SetContent($Content);

You can use either:

$Sample->Title = "Using Classes in PHP";
$Sample->Keywords = "PHP, Classes";
$Sample->Description = "PHP Classes Rock!";
$Sample->Content = $Content;

Or:

$Sample->setTitle("Using Classes in PHP");
$Sample->setKeywords("PHP, Classes");
$Sample->setDescription("PHP Classes Rock!");
$Sample->setContent($Content);

Secondly, think about what kind of data you’re holding in $Sample - Keywords is a list of items, right? So what data type should it really have?

$Sample->setKeywords(array('PHP', 'Classes'));

Which opens up some opportunities, e.g.:

$Sample->addKeyword('Sample');

The ‘var’ notation is deprecated as far as I’m aware. I’d recommend using one of the three visibility keywords: Public, Protected or Private. If you are unsure what these mean, read this.

As for content, what I’d do here is create a class to manage content; this will help you learn polymorphism and inheritance, which are very useful concepts.

Create a base interface called ‘iContent’. Inside this, describe how something would access (not necessarily change) information in classes implementing iContent - functions such as getContent(), getDate(), getTitle() etc.

Then make a simple class which allows you to set text content, a possible date (it would default to today) and a title. Make another which allows you to, for example, load all of this from an XML file. The only things which need to be consistent are the methods of retrieving the information - how they are set is usually completely upto the class itself.

To display the content, pass it to the newPage class. setContent should have a [url=http://php.net/manual/en/language.oop5.typehinting.php]type-hint

 of iContent, which restricts what you can pass to it.

I hope this helps you.

Thanks a lot Jake, 98 views 1 reply :confused:

I’ll be doing some more research and testing, hopefully get back with a updated version.

…it’s a great learning experience.

Thanks :cool:

Don’t worry about interfaces yet. Classes do not need to have interfaces - most won’t.

Thanks Michael.
Yes I’ll get a understanding of classes first then look into the interfaces approach.

This all started when I realized a template would benefit the building process of one of my bigger websites, I currently use <? include (‘includes/header.inc.php’); ?> footer etc and have a couple of sites using the same layout.

Ideally, update 1 class and update 3 sites all at once, if that makes sense. Drop in components as and when I need them, sort of a mini CMS.

I’ll have to do some more reading and try and get a better understanding how things work, not to sure what I’m talking about, that’s why I’m here thanks :slight_smile:

Classes and objects are an abstraction. They try to model the code in a manner similar to the world we live in. Conceptually neat - but it still takes some getting used to. Sometimes the examples the text books give are a bit too vague. Here’s an example from my framework addressing the same problem, sending out a page, but without specific code.

At the base is the Responder class. It’s responsibility is to manage the response to the browser. It extends off of PHP’s inbuilt ArrayObject, meaning that it can be treated as an array and information assigned to it as an array will be used for the response. It’s also abstract, which means that it cannot be directly used - a more specific class than “responder” must be created. That said, it holds methods that all responders need - the ability to compress output, to take a Headers object and so on.

It’s children are the PDFResponder, HTMLResponder, and JavascriptResponder classes. Each class builds a different type of response file. The HTMLResponder is most like what your are doing. It knows how to take it’s array output and bind it to a *.phtml template file to create HTML snippets or even full HTML pages. It has a __toString method which provides it’s html to anything that wants to see the html. This allows html responders to hold each other like blocks on a page.

HTMLResponder has children too - PageResponder builds a full page and has helper methods for preparing the html headers. FormResponder has helper methods for building HTML forms.

The general direction of this code, and of all OOP code, is general to specific. Responder is a very general class - an outline if you will. At the other end FormResponder is very specific - generating only a section of a larger page.

If you’re observant you’ll note that due to this structure FormResponder has information on how to do fully qualified responses (gzip compression) it will never directly use but inherits. This is a limitation in PHP that is to be addressed using Traits in 5.4 - which is a sort of multiple inheritance. But again, don’t worry about that.

For now worry about the core OOP concepts of

Encapsulation - data and methods that act on that data are packaged together.

Inheritance - methods from a parent are treated as methods of the child, allowing child code to address more specific concerns than parents.

Polymorphism - behavior can be modified using overriding methods. This usually involves an abstract class becoming more specific as you move down the ancestry tree.

Abstraction - The class is ideally a “black box”. You don’t need to care about what is going on inside of it, just about the results that it gives. Also it allows you to delegate the definition of behaviors to specific classes. In my example above - Responders must have a “parse” method, but the responder class doesn’t define the method - it requires the children to define it, especially since “parse” is a wholly different process for a PDFResponder object than for a HTMLResponder.