Need help writing first OOP code

I would like to start writing some code for my website using object-oriented style.

Having never written a real app in PHP, I’m intimidated and not sure where to start.

I figured that creating a Log-In screen would be a good place to start.

Does anyone know of any good books or online tutorials or sample code that could help me get started writing PHP OOP?

I guess I need a “Customer” class with properties and methods, right?

TomTees

IMO, a page object or at least it’s rendered result, is what you would provide a response object, which would take care of the specifics of your environment, whether that be CLI, HTTP or stderr, etc.

Cheers,
Alex

Thinking in the context of a page is quite restrictive, I found it much more flexible to construct a ‘response’ object.

It seems to fit a little better, in my opinion, with the webs request/response nature. Accept the request, form a response based on the request and reply (if required).

It allows you, at least contextually, to easily slot in a non-html response like json, xml or even cli.

Whilst still bound too tightly to HTTP for my liking*, maybe Symfony’s Response Object maybe of interest.

*it is in a HTTPKernel package though. :slight_smile:

Building a page object, depending on your requirements, can be very difficult. I have never found a reusable Page object/class I would actually use, for example consider the following basic object:

class Page{
  private $title;
  private $content;

  public function __construct($title = '', $content = '')
  {
    $this->setTitle($title);
    $this->setContent($content)
  }

  public function setTitle($title)
  {
    $this->title = $title;
    return $this;
  }

  public function getTitle()
  {
    return $this->title;
  }

  public function setContent($content)
  {
    $this->content = $content;
    return $this;
  }

  public function getContent()
  {
    return $this->content;
  }

}

This is a very basic class which does nothing but hold contents for a very basic page object. Most people start off with something simple, but depiste it’s simplicity, its that simplicity that makes it reusable. The catch-22 is, it’s so simple why would I use your code when I could write my own in 30 seconds? So most developers do just that.

You will realize it’s use-less-ness and begin adding code to make it more robust, and at this very point you begin breaking solid OOP design principles and turning certian people at every added feature (the opposite effect of what you desired).

For instance, lets say you wanted to extend the functionality, you may use the above as base class and add rendering functionality is a sub-class:


class Page2 extends Page{

  public function build($template_path)
  {
    $smarty = new Smarty();
    $smarty->assign('title', $this->getTitle());
    $smarty->assign('content', $this->getContent());

    $smarty->setTemplate($template_path);

    $smarty->render(); // Assume this echo results to screen automatically
  }

}

Your simple class now has a dependency on Smarty template engine, which many developers despise because of the bloat and added complexity. It’s a little more useful but not much.

One might use your page object like so:


$page = new Page2(`Some title`, `Some web page contents`);
$page->build(`var-some-template-path-home.tpl`);

To make your page object even more interesting, you would probably at some point connect a database object to it and provide all kind of querying functionality, for page selection, creation, updation, deletion, and so on. However this will probably come at the expense of flexibility which means, yet again, you turn off a lot of developers from ever using your library. Perhaps you code it so it`s dependent on MySQL or maybe PDO. What if I need it to meet PG or MSSQL.

This is where OO programming begins to become more of an art than a trivial science. Every accomplished OO developer learns to think and plan for abstractions or flex points in their code. So if someone says to you, can your object work with Twig instead of Smarty and MSSQL not MySQL what is the answer.

Keep things simple, avoid the temptation of throw an entire application into a single object. This is where working with a framework would come in handy. You would learn what a generic framework (ie: Zend) does for you and what you don`t have to repeat in your own objects, like a URI parser for page request-lookup.

Cheers,
Alex

[quote=“Chroniclemaster1,post:15,topic:59248”]

Yes, Congratulations![/quote]

I can handle “tangents” like these.

Thanks to both of you!!

Wish me (long-term) luck!!

TomTees

And I’ll continue to beat the drum of making a class for the basics of a page as a starting point. I can’t imagine a class that one would use more over time.

It doesn’t work like that :frowning:

In my experience, the worst thing you can do is think you are learning by reading a tutorial/book. You can only learn by putting what you read into practice - even if it’s just re-typing rather than copy pasting you will learn several things, but I think you’re probably past that. Basically: solve problems -> read how others are solving them (you are never alone) -> discover better ways to solve problems.

+1. A log in system would be the last thing I would add considering I can just run the application on my PC until I feel it’s ready to be moved online. I would think of an application you would want to make(a todo list manager would be very easy) and get that working first. Take what you learn from there and then apply it to your website. My process is think of the idea, plan the database, figure out what pages I will need, and what are the most common things I will need. The common things you need will be what you build classes and functions for.

I’ll point out in the first book I posted they do functions by chapter 5 and class by chapter 6. The Anthology book does it in chapter 1, but that book is more for, “Here’s this neat thing” vs. building an actual application like the first book does.

I couldn’t agree more, it’s like a secret book of tips-n-tricks. I read this book not 3 weeks ago and I’m still reveling!

Love it.

I didn’t realize there was a limit on posting on SitePoint.

:lol: Yeah, I can identify on both points. And you will certainly be able to go back through those posts and find a lot of good information.

Books can be invaluable if they make sense to you and give you key bits of information that you need. If you’re talking about the Design Patterns book by Eric and Elisabeth Freeman, there is a copy of it sitting on my bookshelf too. That’s one I go back to a lot. You’re right, its at a little higher level but the great thing about it is that it explains WHY the pattern works. And those are simple easy to apply principles in your own OOP, design patterns or no. That is a great book though, because its one of the most readable you’ll find. I would still recommend grabbing Code Complete 2 though. It’s a better book for beginners IMO.

My best guidelines would be LIVE by abstraction. I love to be able to think about a problem at a low to medium level of implementation and be able to think "well, I need to do x which is about cryptography so I’ll call the CryptographyManager to handle that, and I need some database data so I’ll create a DAL object and call one of it’s functions, and I need to create an object y to pass back to whatever function is calling me so I’ll create object Y, and now all my function is really doing is configuring object Y. By borrowing all of the implementation wrapped up in those other abstractions you can see that you don’t need to worry about any of it. I can focus on ONE thing configuring Y. In class Y, all I have to worry about is defining Y, in the Cryptography Manager I just have to deal with that particular function, in the DAL object’s function, I just have to get that one set of data. Abstraction helps you to mentally manage things.

Abstraction gives you the best single set of guidelines to determine what classes you build and what functions / data they have. Then encapsulate, encapsulate, encapsulate. (You’ll notice that 90% of the design patterns in the Freemans’ book is about different ingenious ways to encapsulate “everything”).

For simple log in you don’t really need a class for it. It’s mostly database work as you have the person enter in their alias and password and check to make sure that person is in the database. Yes, you can make a database class to handle as much of your database stuff as needed.

You also could make a class that could be used to generate a web page(header, content, menu, footer, etc.) This way whenever you want to make a page you simply create a new instance of the class and go from there.

Here’s a bare bones look at what it takes for me to make a page.


<?php
	require_once ('constants.php');
	require_once ('page.php');

	$homepage = new Page(TITLE, HEADER, KEYWORDS, FOOTER);
	$homepage->content  = "Hello";
	$homepage->display();
?>

If you need to tweak the page a little, you can create a class that extends the main class. Here’s a sample of my admin class that generates my pages for administration back end for sites.


<?php
	require_once ('page.php');

	class Admin extends Page
	{
		public $buttons = array("Home" => "index.php", "Post" => "posts.php", "Topics" => "topics.php");
	}
?>

For books I would look at the latest version of “PHP and MySQL Web Development” by Luke Willing and Laura Thompson. It’s rather good at covering a lot of the basics. I use “The PHP Anthology” from Sitepoint quite a bit as of late as well(mostly for switching over to using PDO for my database stuff).

Probably a tangent too, but congratulations nonetheless.

I couldn’t agree more with you, Chroniclemaster1!! :wink:

(Finally, a voice of reason!)

OOP is just a variation of procedural programming. It’s mostly about the focus and discipline which come from trying to build larger projects without going insane. If you think of a class as a superstruct, they’re virtually identical, OOP was developed by procedural programmers after all. The biggest difference is that all of your programming code and data have to be grouped into a class (ie in procedural programming you use structs as a best practice to organize groups of data but you don’t HAVE to use them). In OOP that pattern is basically defined as a best practice and made mandatory; everything is grouped into a class (which is usually pretty easy on the one hand until you’re left with a few scraps lying around and have to shove them into a class named something silly like ApplicationHelper (or whatever).

Oh, I think I get OOP theory. I am just finding it harder to apply dry textbook examples to a real-world system. And being a perfectionist, I want to do something that would make the senior members on SitePoint proud of me.

The more I read up on things like MVC, the more I see there are a lot of “OOP Prima Donnas” out there. Clearly, “you get what you pay for”, and a lot of the “help” on websites/blogs across the Internet is filled with bad information.

And so I have been trying to take the various approaches/opinions and get clarifications here so I know that I am using the “right” approach.

In my defense, I asked some pretty basic questions last week. The problem is that many people 1.) Don’t read, and thus 2.) Answer the wrong question, as well as 3.) Going off on tangents. (Some even get mad at “me” when others did that?!)

I don’t mind tangents, but one reason for my “countless other questions” - as Oddz put it - is because simple threads morphed into things that weren’t answering the original question.

(When it is more relevant, I’ll go back and re-read everything, and am sure I’ll find some really helpful gems!)

Far and away, the best book I’ve found on programming in general is Steve McConnell’s Code Complete 2. That’s how I learned virtually everything I know. It’s so sensible, and readable that you’ll probably sit down for your first skim and read it cover to cover. It’s like getting to grab a guru and sit down for several hours to unlock the secrets of the universe. The thing that makes McConnell so great is that he identifies complexity as the number one enemy of any programming project and proceeds to give you all the tools you need to make your life simpler. He also cites numerous other books at the end of each chapter which gives you the perfect platform to jump into more detail on any particular topic you feel like diving into next. Chapter 9 PPP (Psuedocode Programming Process) is one of the most important chapters you’ll read in any programming book ever, but the whole thing is a fantastic overview. The book is designed for all programming languages though most of his examples are in C++ and Java, so he definitely leans strongly toward OOP best practices.

http://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670/ref=sr_1_1?ie=UTF8&s=books&qid=1276367087&sr=8-1

Well, Chroniclemaster1, my main problem got a lot easier after Friday…

I start a contract on Monday after being unemployed for over a year.

Assuming this new gig pans out, I don’t have to spend 90% of my time worrying about paying bills and supporting my household, and now I can maybe step back and take a slightly more leisurely approach to this.

I will likely go back and re-read some books I read last year on Advanced PHP (using OOP) and on OOP. I also think I’m going to try and get through “Head First: OOP Design Patterns”, because even if it is more advanced than I need, it will “expose” me to different ways to conceptualize classes, objects and systems. (A little OOP humor there!) :lol:

At the same time, my wife and I still want to get this business going, so I don’t want to spend to much time “theorizing”.

I have done an excellent job doing my requirements, now it’s time to roll up my sleeves and see if I can finally build my first web app using OOP! :slight_smile:

TomTees

Yes, Congratulations!

I would recommend building the macro aspects of your application before considering the micro ones. A sole Login mechanism doesn’t really do you much good without the developed core or pattern of handling repeat tasks. Just my 2 cents…

Someone said it before in one of your many threads. Think about the core functionality and translate it into OO concepts before taking on individual micro level tasks. You seem to attempting to decorate a house before the blueprint has even been approved when it should be the other way around. At least… that is the impression I get from your countless other questions.

Its not so much the limit, but rather the approach you are using. Sit down and plan out your app.

One of your initial steps would be planning out your database structure.

Also, how familiar are you with sessions and cookies?

Next, when you want to begin the building stage, may I suggest a MVC approach (not a framework).

Once you have your database structure planned out, gained a familiarity with sessions and cookie and understand the suggested MVC approach; the login system should be very straight forward =), after all, all you are doing is simply getting values from the database and comparing it with user input.

Good luck and let us know how you go.

:slight_smile: There is no limit to posting, nor is there a manners filter. Don’t mind oddz, you’ll get good advice from him sometime. (Though apparently not today).

OOP is just a variation of procedural programming. It’s mostly about the focus and discipline which come from trying to build larger projects without going insane. If you think of a class as a superstruct, they’re virtually identical, OOP was developed by procedural programmers after all. The biggest difference is that all of your programming code and data have to be grouped into a class (ie in procedural programming you use structs as a best practice to organize groups of data but you don’t HAVE to use them). In OOP that pattern is basically defined as a best practice and made mandatory; everything is grouped into a class (which is usually pretty easy on the one hand until you’re left with a few scraps lying around and have to shove them into a class named something silly like ApplicationHelper (or whatever).

Far and away, the best book I’ve found on programming in general is Steve McConnell’s Code Complete 2. That’s how I learned virtually everything I know. It’s so sensible, and readable that you’ll probably sit down for your first skim and read it cover to cover. It’s like getting to grab a guru and sit down for several hours to unlock the secrets of the universe. The thing that makes McConnell so great is that he identifies complexity as the number one enemy of any programming project and proceeds to give you all the tools you need to make your life simpler. He also cites numerous other books at the end of each chapter which gives you the perfect platform to jump into more detail on any particular topic you feel like diving into next. Chapter 9 PPP (Psuedocode Programming Process) is one of the most important chapters you’ll read in any programming book ever, but the whole thing is a fantastic overview. The book is designed for all programming languages though most of his examples are in C++ and Java, so he definitely leans strongly toward OOP best practices.

http://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670/ref=sr_1_1?ie=UTF8&s=books&qid=1276367087&sr=8-1

here’s a tutorial about creating a login screen in OOP using zend framework
http://devzone.zend.com/article/3322

for beginners, this book is great
Build Your Own Database Driven Web Site Using PHP & MySQL, 4th Edition

good luck

That is a valid point, but at no time have I mentioned a “Log In System”.

In my other post, I was asking help creating a class structure for the Registration Process.

And second to the Catalog - which is much harder to implement - that is one of the first functional things that my website needs.

TomTees