webdevRefinery Forum: The Backwards PHP 5.3+ Guide - webdevRefinery Forum

Jump to content

  • 3 Pages +
  • 1
  • 2
  • 3
  • You cannot start a new topic
  • You cannot reply to this topic

User is online Kyek 

  • Founder of wdR
  • Group: Administrators
  • Posts: 4834
  • Joined: 20-February 10
  • LocationPhiladelphia, PA, USA
  • Expertise:HTML,CSS,PHP,Java,Javascript,Node.js,SQL

Posted 10 October 2010 - 06:41 AM (#1)

The Backwards PHP 5.3+ Guide


For PHP beginners and OOP/MVC beginners
The Backwards PHP 5.3+ Guide
A tutorial by Kyek, started October 8, 2010


A quick introduction
Every PHP guide I've seen on the internet or in books teaches PHP in the wrong direction. They tell you the commands, the functions, the loops, the arrays, and only at the very very end do they teach you how to use classes and objects, and almost none of them touch patterns like MVC. So by the time you get to that point, you're already so used to writing awful code that organizing it in logical pieces just seems like a hassle. Impossible, even, if you've already gotten into a project by that point. This guide puts an end to that, and teaches PHP backwards -- the right way. You'll learn classes and object first, then the commands, functions, loops, and arrays to put inside of them -- using the MVC pattern the whole time. If this sounds like a whole lot of gibberish, keep reading ;-)


Chapter 0: Before You Begin
Know What PHP Is!
A lot of people think they need to learn PHP without actually knowing what it is. So here goes: PHP is a scripting language that webservers run to produce a webpage before sending that webpage to your users' web browsers. PHP is *not* code that executes inside of people's web browsers -- to do that, you need Javascript. PHP can only be read and run by your server itself, and the browser simply shows you the result. A simple example of this is that PHP allows you to print the current date out on a webpage. Then, if you right-click the page in your browser and hit "View Source", you'll see the date right in there, as though you typed it directly into the HTML file and uploaded it yourself.

Know If You're Ready To Learn It
PHP is a great language and very easy for programming beginners to pick up. But before you can use it effectively for websites, you need to have a good understanding of HTML and CSS -- and it really doesn't hurt to have decent knowledge of Javascript, either. If you're weak with your HTML code, though, you'll want to bone up on that before continuing.

Setting Up Your Environment
Before beginning this guide, you need to have a PHP development environment set up on your own personal computer. Some folder where you can put PHP files, load up a URL that starts with http://localhost in your browser, and see the result of your code. Later, you'll also need a MySQL server running on your computer, preferably with a copy of PHPMyAdmin preinstalled. If you're on Windows, the fastest and easiest way to get up and running is by downloading a free copy of WAMP. Mac users can use MAMP. Setting up your environment some other way? Just make sure your version of PHP is 5.3 or higher!


Chapter 1: Hello, World! (or, intro to classes and functions)
Writing the PHP
If you're a veteran programmer, you know that writing an application that prints "Hello, World!" is generally the first program you write when learning a new language. If you're not a veteran programmer, I have a fun fact to share with you! Writing an application that prints "Hello, World!" is generally the first program you write when learning a new language!

To do this, we're going to use two PHP files. Seems like overkill for printing one whole line of text, I know-- but there's method to the madness! So find the root folder of your development environment -- the "webroot" -- and we'll start from there. If you're using WAMP or MAMP, consult the documentation if you can't find what folder that is. Within the webroot, create the path 'lib/mysite/controllers' to drop HelloController.php into, and put index.php in the webroot itself.

lib/mysite/controllers/HelloController.php
<?php
namespace mysite\controllers;

class HelloController {

    public function sayHello() {
        echo "Hello, World!";
    }

}

?>


index.php
<?php
require_once(__DIR__ . "/lib/mysite/controllers/HelloController.php");

use mysite\controllers\HelloController;

$site = new HelloController();
$site->sayHello();
?>

Load up index.php in your browser, and ta-da! It says "Hello, World!"

Understanding the PHP
I'll be honest: If this were any other PHP book, it would have told you to make one PHP file with the line
<?php echo "Hello, World!"; ?>
in it and call it a day. But writing a site like that is bad form. The reason why that's bad form, as well as many of the technical things that make this more advanced code, are all things you'll learn slowly over the course of this guide. For now, let's go through this code to get just a basic understanding of what each line does, and we'll revisit any interesting pieces later.

lib/mysite/controllers/HelloController.php
Most good webapps are designed with what's called an "MVC", or "Model, View, Controller" pattern. MVC is a guideline for how to separate different kinds of functionality so that your code stays clean and easy to maintain. We'll work more with this as we go, but for now, know that the "Controller" part of MVC is the part that has the "Business Logic" -- a fancy way of saying that the Controller is what loads a page, knowing all the work that needs to be done to get to that point. For now, we're starting nice and easy. So let's get into the file itself!

<?php

In order to tell your server what's PHP code and what's not, we use <?php ?> tags. Anything inside of those tags will tell the server "I'm code! Run me!", while anything outside will be sent to the web browser like any other text or HTML. Soon, we'll try mixing HTML and PHP together using this concept; for now, though, all of our PHP files will start with <?php and end with ?>. Now you understand the first and last lines of HelloController.php ;-)

So let's hit the real first line, now:
namespace mysite\controllers;

This tells PHP that everything in this file will belong to the "mysite\controllers" namespace. Namespaces are simple -- they're just a way to make sure that the names of classes, functions, and variables in your code don't get inadvertently changed or overwritten by someone else's code that uses similar names. As long as your namespace is unique, you're safe. Namespaces can be anything, but they're most useful when you make the namespace the same as the path to the file. So, ignoring the 'lib' folder because we want our namespace to start with the app name, HelloController is in mysite/controllers. We flip the forward-slash to a backslash (the official separator for namespaces), and we have it :)

class HelloController {

Almost all the code in your webapp will exist inside of a "class", or a big group of code all meant to perform a similar task. That opening-brace (the '{') means that any code after it and before the closing brace ('}') will belong to the HelloController class. The name of that class is arbitrary -- we could call it "class Sharkbait_HuHaHa" and it would still work just fine.

public function sayHello() {
    echo "Hello, World!";
}

Functions are blocks of code that you can call over and over and over again. This particular function is named "sayHello", because all it does is print out "Hello, World!" to the browser. You might have already assumed that the 'echo' command just prints out text-- and if you did, then you're learning pretty quickly :). So every time we tell the "sayHello" function to run, it'll print "Hello, World!". That 'public' keyword just tells the class that we're allowed to run this function from code that's outside of the class. If that doesn't make sense yet, it will in just a little bit.

index.php
<?php

Again here, the file starts with <?php and ends with ?> to let the webserver know that everything in the file is PHP code. With that, let's move on:

require_once(__DIR__ . "/lib/mysite/controllers/HelloController.php");

It would be cool if PHP could magically "find" all the class files that we want to use, but unfortunately it's not that smart quite yet. Until then, we can use a built-in function called require_once to load any PHP files that we might need to use. Since index.php is the file that we're actually loading with the browser, we use require_once to load in the contents of any other PHP file we'll need to show the page. All we have to give it is the path. We start with __DIR__, which is a keyword that PHP will automatically replace with the absolute path to the current file, index.php. This might be something like "C:\Users\Barney\TheOnlyThingOnMyComputerThatIsntPorn". After that we have a single '.', which, believe it or not, is actually a command in PHP. It's called a 'concatenator', and any two "strings" or lines of text that it falls between, it will join together. So we join together your current path with the path from here to the file we want, and ta-da, require_once has everything it needs!

use mysite\controllers\HelloController;

Remember how namespaces keep your code from conflicting with other similarly-named code you might be using? Here's why. For any class you've loaded in with require_once and now want access to use, you just tell PHP to 'use' it. You specify the class by typing its namespace, followed by the class name itself. Now, any time we use HelloController in our code, it will know that what we really want to use is mysite/controllers/HelloController :)

$site = new HelloController();

Classes are like blueprints. They have all the data you need to make something useful, but you need to build the object before you can start using it. So to make an object from our class, we need a few different things:
$site
in PHP, anything starting with $ is called a variable. A variable can contain numbers, text, or even Objects, a usable version of our blueprint class. All we do now that we have a variable is create a, *cough cough*, new HelloController object. Then we take that new HelloController object, and insert it into our variable, $site. This is pretty hard to understand until you use it, so let's use it!

$site->sayHello();

So we know that $site now has all of the HelloController class's code hiding inside of it, and we know that we need to run the "sayHello" function in order to print "Hello, World!" to the screen. Thankfully, this process is very easy :). First, we type $site since that has the function that we want to call. Then we type an arrow ("->") to tell PHP that we want to do something "inside" of $site. We know that sayHello is "inside" of $site, so we type that next. Ta-da, we just ran our sayHello function! With PHP, functions can be a little more complex and allow you to pass data back and forth between them. Normally you'd add more variables between those parentheses () to do that (just like we did with require_once!), but since we don't need to in this case, we just leave them empty.

Feeling Overwhelmed?
That's ok! Because I'll let you in on a little secret: what you just learned is the hardest part of PHP. I warned you that you'd be learning this language backwards ;-). All of our code from here on out will be written in classes and functions, so if you're not quite grasping what they are and why we use them now, just keep on reading and you'll settle into the idea when we use it more. Just feel safe in knowing that it all gets easier from here.


Chapter 2: More Pages! (or, intro to conditionals)
Less is More, but One is Everything.
Good webapps separate the logic for each page into different PHP files. Great webapps split each page into separate files, but load them all through index.php! Sound crazy? Let's do it, then you'll see how easy your life becomes.

A Controller with a View
We've gone over what the Controller is in the Model View Controller structure -- now, let's talk about the View. In our Hello World example above, we're simply echoing out some text. But for most pages, we're going to need a lot more than that! You don't want to echo out things like "<html>" and "<title>My Site</title>" because not only is that a lot of PHP code, it would get incredibly messy. The best thing to do is write a plain old html file, but add bits of PHP code to output any variables you need to display.

Telling Controllers Where to Find Views
If the controller is going to be responsible for loading these HTML pages, it has to know where to find them! So let's add a line to the very top of our index.php:

index.php
<?php
define("VIEW_PATH", __DIR__ . "/views");

require_once(__DIR__ . "/lib/mysite/controllers/HelloController.php");

use mysite\controllers\HelloController;

$site = new HelloController();
$site->sayHello();
?>


define() is another built-in PHP function. You use it to make a very specific kind of variable called a "Global Constant". Global constants are available from any file or class within your application, and can never ever be changed while the PHP script is executing. In this new line, we're making a new global constant called "VIEW_PATH", and using the same __DIR__ and concatenator syntax that we used in the require_once call to define a path to a "views" folder off of the webroot. Now, any controller that needs to load a view has a way to find the view files!

The Calculator Page
So, knowing about Views, we're going to create three files to make a page that can add two numbers together: A Controller, a View for the calculator form, and a View for the calculator results page. Here are the files -- and remember, these paths should come from the webroot!

views/calc_index.php
<!DOCTYPE html>
<html>
	<head>
		<title>My Site : Calculator</title>
	<head>
	<body>
		<form method="get" action="index.php/calc/results">
			<input type="text" name="num1" />
			<input type="text" name="num2" />
			<input type="submit" value="Add!" />
		</form>
	</body>
</html>


views/calc_results.php
<!DOCTYPE html>
<html>
	<head>
		<title>My Site : Calculator Results</title>
	<head>
	<body>
		The answer is <?php echo $answer; ?>!
	</body>
</html>


lib/mysite/controller/CalcController.php
<?php
namespace mysite\controllers;

class CalcController {

	public function index() {
		require(VIEW_PATH . "/calc_index.php");
	}

	public function results() {
		$answer = $_GET['num1'] + $_GET['num2'];
		require(VIEW_PATH . "/calc_results.php");
	}

}
?>


Picking out your URL scheme
Now we have a Controller that loads the Views and that's awesome -- but before we can actually load this page, we need a dispatcher! A Dispatcher (often called a "Router" as well) is a block of code responsible for looking at the URL you're loading, and passing your request off to the correct Controller. In our case, we'll be looking at the URL and deciding if we should load up HelloController or CalcController. So the first step is figuring out what URLs we're going to use!

We already know that we have to load index.php. So there's a couple options for how to add extra information to a URL without actually changing the file you're loading -- and since this is the backwards PHP guide, I'll start you with the best and most advanced solution: PATH_INFO! :) We're going to load your pages with these URLs:
index.php/hello
index.php/calc
index.php/calc/results (this is your calculator results page)


Believe it or not, adding a slash and then more info after your .php file will still load the PHP file. What's more, the PHP engine will even create a variable for you to read what extra info was included!

Adding your dispatcher to index.php
Here's the index.php with our Dispatcher AND the require_once line to bring in our CalcController. Once this is in, you can load the pages with the URLs I gave above. But keep reading, because this does you no good unless you know how it works ;-)

index.php
<?php
define("VIEW_PATH", __DIR__ . "/views");

require_once(__DIR__ . "/lib/mysite/controllers/HelloController.php");
require_once(__DIR__ . "/lib/mysite/controllers/CalcController.php");

use mysite\controllers\HelloController;
use mysite\controllers\CalcController;

// Request dispatcher
if ($_SERVER['PATH_INFO'] == "/hello") {
	$controller = new HelloController();
	$controller->sayHello();
}
else if ($_SERVER['PATH_INFO'] == "/calc") {
	$controller = new CalcController();
	$controller->index();
}
else if ($_SERVER['PATH_INFO'] == "/calc/results") {
	$controller = new CalcController();
	$controller->results();
}
else {
	echo "You must choose a page!";
}
?>


Wow, all kinds of new stuff there! First, two lines I don't need to explain: The extra require_once for CalcController, and the second 'use' line for CalcController with its namespace. Those are just there to load our CalcController class, just like the lines for HelloController. And another thing that's super easy to explain:
// Request dispatcher
This line is called a "comment". Any line that starts with a double-slash "//" is considered a comment, and you can type anything you want there without it affecting your code. It's good practice to drop in comments for any piece of your program that might need more explanation if someone else were to read your code.

But now we're getting into some logic we've never seen: IF statements! An 'if' statement allows you to write some expression that can boil down to "true" or "false". For example, let's say you type:
if (4 > 9000) {
	// Do something here...
}
You'll never reach the "Do something here" section, because 4 is obviously not over 9000 -- so it's "false". But if I were to type:
if (1 == 1) {
	// Do something else...
}
1 is definitely equal to 1, which is "true", so any code we put inside of those curly braces will run!

Let me pause quick to talk about that '==' sign: That looks crazy, right? I mean, in all of our old math classes, we just used one = sign to say if something was equal to something else. In the programming world, though (and this is true for nearly ALL programming languages), the single = sign is to assign a value to a variable. So saying:
if ($myVar = 2)
wouldn't actually compare $myVar with 2 to see if they're equal -- it would literally put the value of 2 into the variable $myVar, overwriting whatever $myVar was already holding. That's bad news! So for comparisons, we use double-equals signs. There's also triple-equals signs, but that's more advanced stuff that we don't need quite yet :). For now, know that this:
if ($myVar == 2)
will see if the variable $myVar ALREADY contains the value 2, and if not, will return "false" so that the code inside of that if-statement doesn't run.

[[ To Be Continued! ]]
10


User is offline Smarag 

  • Group: Members
  • Posts: 552
  • Joined: 08-March 10
  • Expertise:HTML,CSS,PHP

Posted 10 October 2010 - 06:44 AM (#2)

I just got an orgasm when I saw the title <3. Will read now ^o^.
0


User is offline NoizeMe 

  • Group: Members
  • Posts: 591
  • Joined: 06-May 10
  • LocationGermany
  • Expertise:HTML,CSS,PHP,Java,Javascript,Python,Node.js,SQL,MongoDB,CouchDB,Cassandra

Posted 10 October 2010 - 11:02 AM (#3)

Nice guide, no kidding BUT I can think of a lot of trouble for folks that is not used to OOP at all.
IMO you should explain a few basic terms of OOP patterns at first before getting into programming at all.
Posted Image
0


User is offline Renegade 

  • Group: Members
  • Posts: 718
  • Joined: 08-March 10
  • Expertise:HTML,CSS,PHP,Javascript,Node.js,SQL,Graphics

Posted 10 October 2010 - 11:17 AM (#4)

Kyek, this is brilliant.
GithubTwitterDribbbleForrst
We all die. The goal isn't to live forever. The goal is to create something that will.

Array(16).join({}-{}) + " Batman!";
0


User is offline BokTheGolem 

  • Group: Members
  • Posts: 668
  • Joined: 04-April 10

Posted 10 October 2010 - 11:51 AM (#5)

THE RING OF FIRE!

Anyways..... amazing tutorial that taught me a lot about how you structure and do things but honestly it just doesn't feel like a novice tutorial to me. Once again it's great material and has tons of good info but it feels like some weird amalgamation of a novice and advanced tutorial. I completely understand why you structured it that way, people probably due pick up terrible habits learning the forwards way and hopefully im wrong. Hopefully newcomers pick this up in a snap but if this were my first programming language this guide might confuse me a little. Not a lot but it doesn't seem like the easiest way to learn, especially if you have no programming experience and have only done html and css.

Once again great guide.
"You can't make me look! I'll just shut my eyes."
"Oh, you'll open them. You have to breath sometime. "
0


User is offline derTechniker 

  • BadBoy™
  • Group: Members
  • Posts: 1183
  • Joined: 06-July 10
  • LocationAustria
  • Expertise:HTML,CSS,PHP,Javascript,SQL

Posted 10 October 2010 - 12:33 PM (#6)

I think this is a great tutorial. I wish i would had learned that back when i got in touch with php. Thanks Kyek!
0


User is online Kyek 

  • Founder of wdR
  • Group: Administrators
  • Posts: 4834
  • Joined: 20-February 10
  • LocationPhiladelphia, PA, USA
  • Expertise:HTML,CSS,PHP,Java,Javascript,Node.js,SQL

Posted 10 October 2010 - 02:51 PM (#7)

Thanks guys :) This is far far FAR from being anywhere near finished, but I wanted to put it up to get some reactions. So, thanks for the reactions :)

@Bok and Noize: That's what I was afraid of :). I'm trying to find a good balance between the advanced stuff that's normally taught last and easing people into the basics, but I definitely agree that I'm not there yet.

What I'm trying to do is teach PHP just like EVERY strictly typed programming language is taught. Java, for example: In Java, there's no such thing as code outside of a class or even (with the exception of initializing variables) outside of a function. So every Java book there ever was teaches you what a class and a function is straight off. C/C++ and many other languages are similar. It wasn't until scripting languages gained popularity again that the concept of code outside of containers got popular, so a lot of people who call themselves developers today think that using classes and programming patterns is something unnecessary. And while they may be right for tiny sites, any application that has a level of complexity really requires that you think in terms of objects and packages in order to keep the code from getting unwieldy.

So while I knew going into this that the very first thing I'd be teaching is what a 'class' is, forcing people into the MVC pattern so early on may not have been the best choice. I'd love to keep that if I can, because the earlier you start thinking in terms of MVC, the easier it is to get your mind around how to build a new webapp... but I may need to restructure what I have so far before I write any more. At the VERY least, I need to cover writing the dispatcher before I even give the code for CalcController and its two views, because I'm throwing all that (slightly more) advanced code at people, then I'm all "Ok let's table that for now and talk about this completely DIFFERENT section of code while you forget about what I just wrote." Not smart of me xD

So yeah -- definitely good observations, thanks :). And @Noize: what OOP concepts do you think I glossed over too quickly? My goal was to introduce the terms more casually in ways that they would make more sense (such as building an object from its blueprints, for example) but if that didn't land well enough, I definitely need to revisit my approach there.

Thanks again everyone :) This one will probably take me a good long while to finish, but hopefully it can help people out a bit before then.
0


User is offline TheDevMan 

  • kthnxbai AKA |{7|-||\|xb41
  • Group: Members
  • Posts: 617
  • Joined: 04-April 10
  • LocationIllinois, USA
  • Expertise:Graphics

Posted 10 October 2010 - 03:01 PM (#8)

Dude, publish a book
Posted ImagePosted ImagePosted Image
If someone has helped you out, or you like their post, click on the Posted Image sign under their reply :)
2


User is offline derTechniker 

  • BadBoy™
  • Group: Members
  • Posts: 1183
  • Joined: 06-July 10
  • LocationAustria
  • Expertise:HTML,CSS,PHP,Javascript,SQL

Posted 10 October 2010 - 03:05 PM (#9)

View PostKyek, on 10 October 2010 - 02:51 PM, said:

So while I knew going into this that the very first thing I'd be teaching is what a 'class' is, forcing people into the MVC pattern so early on may not have been the best choice. I'd love to keep that if I can, because the earlier you start thinking in terms of MVC, the easier it is to get your mind around how to build a new webapp...


Keep that. I think its a REALLY good way to learn php as i know the other side (like probably most of you here). Learning how to code crappy and then switch to OOP is much harder than actually start with the hard part.

Also, if someone understands the hard part at the very beginning, learning is just so much more fun.
0


User is offline NoizeMe 

  • Group: Members
  • Posts: 591
  • Joined: 06-May 10
  • LocationGermany
  • Expertise:HTML,CSS,PHP,Java,Javascript,Python,Node.js,SQL,MongoDB,CouchDB,Cassandra

Posted 10 October 2010 - 04:56 PM (#10)

@Kyek:
I used to get in a similar trap :D.
Keep in mind that these kind of things are daily-business for us and we take things for granted.

For example the term "object".
Instantly we thing about a class with methods, properties and the whole construction and deconstruction stuff.
But try to think out of the perspective of someone who never ever get in touch with this terms.
He doesn't have any idea what you are referring to.

If you take it even further to design-patterns like MVC, you already need a strong understanding of OOP.
So why should I use interfaces?
Why should I split up my logic in such a way?
And most important: Why should I limit my self in such a way?

You won't see a good thing if you are not used to OOP and much more important if you never worked on a bigger project.
As you lined out procedural programing works just fine on smaller projects and it does even for bigger projects if you never need to change your code ;D.
Design-Patterns and OOP in general were developed, because experienced programmers, who had seen a lot projects, ran into problems with maintaining large code-bases.
Someone who is completely new to programing has no idea of maintaining large code-bases, so he wound see a benefits of design-patterns.

If you want to teach people to write clean code, you need to explain first why writing clean code is so important.
And still I would assume that many people still won't get it.
Of cause it would be nice to teach PHP in a good, clean way, but in my opinion this is not possible if you want to address people with a little or none programming experience.

Sorry for the strange English, but I'm kinda tired :D.
Posted Image
0


User is offline Daniel15 

  • dan.cx
  • Group: Moderators
  • Posts: 3038
  • Joined: 17-April 10
  • LocationMelbourne, Australia
  • Expertise:HTML,CSS,PHP,Java,Javascript,SQL

Posted 10 October 2010 - 05:37 PM (#11)

Now THIS is a tutorial. Very nice :D
I just realised the other day that I should really upgrade my server to PHP 5.3 and start using namespaces. Every WordPress extension I've written for my blog has "Daniel15" at the start of the class name... A kinda bad way of doing namespaces. Last time I upgraded a whole bunch of stuff broke though, so I'll have to make sure other people on the same server update their broken stuff. :P

Quote

class Sharkbait_HuHaHa

:D

Quote

For example the term "object".
Instantly we thing about a class with methods, properties and the whole construction and deconstruction stuff.
But try to think out of the perspective of someone who never ever get in touch with this terms.
He doesn't have any idea what you are referring to.

I'd have to agree with NoizeMe there. I think you may have written an OOP introduction (can't remember), so maybe link that or post the most important bits :).

Quote

Sorry for the strange English, but I'm kinda tired .

Your English is fine! :)
Daniel15! :D
Repeat after me: jQuery is not JavaScript. It is not the answer to every JavaScript-related question. When you have to write some JavaScript, do not instantly react with "Oh, I'll do that with jQuery!"

javascript:alert((''+[][[]])[!+[]+!+[]]+(![]+[])[+!+[]]+(''+!+[]/[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(''+!![])[+!+[]+!![]+!![]]+(![]+[])[!+[]+!+[]]+(+!+[])+(!+[]+!+[]+!+[]+!+[]+!+[]))

View PostKyek, on 16 November 2011 - 11:14 AM, said:

Daniel15 is ruining my life D:

View Postmorrison_levi, on 30 September 2011 - 04:10 PM, said:

They added more features to tables because. . . oh, yeah, they do have valid uses! Ever heard of data? We do still use that. :)
0


User is online Kyek 

  • Founder of wdR
  • Group: Administrators
  • Posts: 4834
  • Joined: 20-February 10
  • LocationPhiladelphia, PA, USA
  • Expertise:HTML,CSS,PHP,Java,Javascript,Node.js,SQL

Posted 10 October 2010 - 07:56 PM (#12)

lmfao, of all the people to get the Sharkbait_HuHaHa joke, it's the one wdR member who lives geographically closest to 42 Wallaby Way xD. But yeah -- 5.3 has a couple backward-compatibility issues to watch out for, but it is so so totally worth it. Namespacing isn't even the biggest thing. For me, what made 5.3 so incredible was late static binding. If a class can't refer to its overridden static members, it can hardly be called an OOP language. That, closures, the advanced OpenSSL stuff ... namespaces are just the cherry on top ;-). My last gripe is the uselessness of the 'private' keyword. If they would change namespaces to packages, allow children to access parents' private members, and allow classes within the same package to access protected members, I would totally be sold. Actually no. Then I'd probably bitch about the needle/haystack thing ;-)

But yeah, back on topic...
Good call on my use of the word 'object'. I was thinking that the way I started using the word sufficiently explained it, but to someone who has never programmed before, that's a hard concept to grasp in passing. I'll change that :) Thanks guys!

As for things like convincing people that MVC-patterned OO code is better than procedural, though, I'm not sure that's necessary. After all, this tutorial is geared toward folks who are either learning their very first programming language, or their very first web language. Not only would they not know the difference between procedural-style code and OO code, I'm not even presenting that as an option. To the lay person, this is how you HAVE to program PHP. Drawing another parallel to pretty much every Java book out there, since you HAVE to start with advanced OO concepts, they just give it to you straight-out. Most don't even describe why a class is important-- they just leave you to assume that classes are logical groups of code, which is exactly right anyway. If that's your first modern language, you don't ever question that there might be another way to do it -- you're told that you need to use a class, and you do. Done.

So I think that telling people they need Controllers and Views and such is fine, since my demographic is a group of people that don't even need to be aware that there are horribly dirty alternatives that they shouldn't use :). Other common patterns like Singleton and Factory, and other concepts like abstract classes and interfaces, are all things that I can get into later in the tutorial when the "project" it teaches from has a use for those things. Singleton I'll introduce when we need a Config object. Factory I might introduce for database connections if I'm feeling especially outgoing. I don't need to teach all of the important parts of OOP at once, I just need to teach enough that a very basic MVC structure can be established :)
0


User is offline BokTheGolem 

  • Group: Members
  • Posts: 668
  • Joined: 04-April 10

Posted 10 October 2010 - 09:27 PM (#13)

View PostKyek, on 10 October 2010 - 07:56 PM, said:

lmfao, of all the people to get the Sharkbait_HuHaHa joke, it's the one wdR member who lives geographically closest to 42 Wallaby Way xD.


You didn't get my reference when I said "THE RING OF FIRE!" then :(

Oh well. And some tutorials i would LOVE to see are tutorials covering factory classes and singleton patterns. I think i have singleton down (at least to my understanding) but all that other stuff seems interesting.
You know what, i might actually use my AP Computer Science classes productively now and not just build up my minecraft empire (although he wiring in that is fun. I had to construct some circuits to maintain my automated train system, although it didn't work in the end because of limitations by the game. Although it's fun using the stuff like circuits i learned in my computer tech clases in a game.)
"You can't make me look! I'll just shut my eyes."
"Oh, you'll open them. You have to breath sometime. "
0


User is online Kyek 

  • Founder of wdR
  • Group: Administrators
  • Posts: 4834
  • Joined: 20-February 10
  • LocationPhiladelphia, PA, USA
  • Expertise:HTML,CSS,PHP,Java,Javascript,Node.js,SQL

Posted 10 October 2010 - 09:35 PM (#14)

Oh lord, I completely glossed over that reference xD Nicely done xD

But yeah -- there are a bunch of "dumb" patterns that they teach you in those classes... like basic usage of an abstract, for example, which I really don't count as a "pattern". But Singleton and Factory are two that I have a really difficult time writing a decent program without. I'll try to touch on both in here :)
0


User is offline BokTheGolem 

  • Group: Members
  • Posts: 668
  • Joined: 04-April 10

Posted 10 October 2010 - 09:45 PM (#15)

This is sorta offtopic but your here right now and it does have to do with php and the ilk so here's a question i've been meaning to ask for a while.

I have been wondering, how abstract should my functions and thing's be? I used to write my functions as ambiguously as possible because I always thought "Why have two function's do their own jobs well when I can have one do both messily!" It got to a pint where I thought I might as well write a framework because the way my code went all my projects basically ran off their own framework. I have like 3 different "sorta frameworks" that I could probably interchange between projects with some effort. I guess having a framework would be a good thing but i'm just wondering exactly how abstract should your code be? As an example you have the say hello function, my code would look something like this, remember I really enjoyed writing ambiguous functions.

<?php
class TextController {

    public function sayText($text) {
        echo $text;
    }

}

?>


I mean thats a really basic example but you get what i'm saying? I always thought having a function to say hello and only say hello seemed like a bad idea. So in short how abstract should my code be?

Edit: is my code right there? I've been jumping around objective-c, php/html/css, and java i keep intermixing the languages...
"You can't make me look! I'll just shut my eyes."
"Oh, you'll open them. You have to breath sometime. "
0


User is offline derTechniker 

  • BadBoy™
  • Group: Members
  • Posts: 1183
  • Joined: 06-July 10
  • LocationAustria
  • Expertise:HTML,CSS,PHP,Javascript,SQL

Posted 19 November 2010 - 03:27 AM (#16)

View PostBokTheGolem, on 10 October 2010 - 09:45 PM, said:

Edit: is my code right there? I've been jumping around objective-c, php/html/css, and java i keep intermixing the languages...



The code is fine.

On the other question i have no answer as i'm really asking myself the same thing. :rolleyes:
0


User is offline Dissident 

  • Group: Members
  • Posts: 144
  • Joined: 08-March 10

Posted 25 November 2010 - 03:02 AM (#17)

At first I was skeptical that people should learn the OOP mechanisms of PHP before they learned some of the simple stuff, but this tutorial outlines that pretty damn well. Good work, Kyek!
0


User is offline Shadower856 

  • Group: Members
  • Posts: 138
  • Joined: 15-October 10
  • Expertise:HTML,CSS,PHP,Javascript

Posted 22 December 2010 - 12:22 AM (#18)

View PostKyek, on 10 October 2010 - 06:41 AM, said:

<?php
// Request dispatcher
if ($_SERVER['PATH_INFO'] == "/hello") {
	$controller = new HelloController();
	$controller->sayHello();
}
else if ($_SERVER['PATH_INFO'] == "/calc") {
	$controller = new CalcController();
	$controller->index();
}
else if ($_SERVER['PATH_INFO'] == "/calc/results") {
	$controller = new CalcController();
	$controller->results();
}
else {
	echo "You must choose a page!";
}
?>




Wouldn't it be better (and easier) to use:
<?php
// Request dispatcher

//Using switch + no evil double quotes =)
switch($_SERVER['PATH_INFO']) {
    case '/hello':
        $controller = new HelloController();
        $controller->sayHello();
        break;
    case '/calc':
        $controller = new CalcController();
        $controller->index();
        break;
    case '/calc/results':
        $controller = new CalcController();
        $controller->results();
        break;
    default:
        echo 'You must choose a page!';
        break;
}
?>

0


User is offline ThatRailsGuy 

  • José the Jalapeño ... on a Stick
  • Group: Members
  • Posts: 4387
  • Joined: 02-October 10
  • Expertise:HTML,CSS,PHP,Java,Javascript,Ruby on Rails,SQL

Posted 22 December 2010 - 12:24 AM (#19)

Is the break; needed? But over all, yeah that's way better :P Kyek just got severed by Shadower856.
Posted Image Reliable Rabbit
Reliable Rabbit, my "company."
0


User is online Kyek 

  • Founder of wdR
  • Group: Administrators
  • Posts: 4834
  • Joined: 20-February 10
  • LocationPhiladelphia, PA, USA
  • Expertise:HTML,CSS,PHP,Java,Javascript,Node.js,SQL

Posted 22 December 2010 - 07:01 AM (#20)

Guys, this is intended to be a general PHP guide for beginners... As not-done-yet as it is. We hadn't touched switches yet and had barely used if-statements, so I think it's better to show a chain of else-ifs before showing the shortcut to them :)

(and yeah, all the breaks are required but the last one. Without the breaks, it would keep moving down the switch after the controller function was called and execute other controllers)
0


Share this topic:


  • 3 Pages +
  • 1
  • 2
  • 3
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Enter your sign in name and password


Sign in options
  Or sign in with these services