Month: January 2017

PHP Autoloader

PHP Autoloader

The autoloader is similar to a troll riding a unicorn on a purple rainbow. You know it happens on a daily basis, but you’ve never seen it happen, even though you wish you had.

If you read my last post about “My PHP Story,” then you may know I’ve been using PHP since before the autoloader came to be a thing. We would always include all of the files we needed using a single file or on the fly when we needed them. When I first read about the PHP autoloader, I was a bit confused and wondered where that troll got his unicorn, but now I use it every day (like a boss).

How It Helps

There may be more benefits to using the autoloader than the ones I mention, but here are some of my favorite ways it helps.

  • One include file, instead of many
  • Cleaner code since there are less includes
  • Composer can generate it for you
  • Only classes you are using get included

It simplifies the inclusion of a file based on the instantiation of a class. So, when you instantiate a class, it includes that file.

Using An Autoloader

There are two ways that I know of to use an autoloader, and I’ll list both. The second way is my preferred way.

Make Your Own

As with most things, you can always make your own. In most cases, you won’t want to do this, and you should use Composer. Below is a very basic example of making your own autoloader. This example is also using a closure, but I’ll talk more about those another time.


<?php
spl_autoload_register(function ($className) {
    include $className . '.php';
});

As you can see from the example above, it accepts a parameter called $className, and it then uses that to include the file that corresponds to that class. That is all you need to do. You would then include this file at the top of your PHP scripts and instantiate your classes.

Using Composer

Yay! Composer! If you reference the composer.json file below that I pulled from my PHP project boilerplate, then you’ll notice the autoload PSR-4. You can then run composer install or composer dump-autoload, and it will generate an autoloader for you.


{
  "name": "wappr/library-name",
  "description": "",
  "version": "0.1.0",
  "license": "MIT",
  "keywords": [""],
  "autoload": {
    "psr-4": {
      "wappr\": "src/"
    }
  },
  "require": {
    "php": ">=5.6"
  }
}

Then you will include vendor/autoload.php at the top of your PHP files. This will allow you to instantiate your classes and have them included by the autoloader.

Conclusion

I hope this helps you understand autoloading. You may not struggle with it like I did and I hope you don’t. If you do, feel free to email me, and I’ll help you out.

My PHP Story

My PHP Story

In an attempt to help people understand you won’t learn everything overnight, I would like to share with you, my story. This story starts in the early 1990s. I hope this is a post that everyone can read and understand.

My Programming History

One of my neighbor’s, his dad was a programmer, and they had a computer. We were getting on the internet before a lot of people even heard about it. We were doing this before AOL, CompuServe, Juno, and other dial-up providers. My friend’s dad would also show us how to write BASIC, and we were hooked. They had a book of programs, so we would type them into the computer and play those games. Most of the time we would have a typo and spend our time trying to find it.

My love for programming continued into middle school and high school. In high school, I started learning ASP and helped a friend program the school’s website. It was an AccessDB driven site using OBDC to connect, and it was awe-inspiring.

ASP was okay, but I wanted to learn more, so I started learning PHP.

Starting PHP

I started with PHP 4, and I’m still using PHP today. Don’t worry; I have upgraded since then.

At first, PHP seemed rather confusing and complicated, but I kept writing. I’m sure my PHP was terrible then, but that didn’t matter; it was important that I kept writing it. I probably did everything the way you shouldn’t do it, and that’s okay. Write it, so you understand it, and if it works, that is awesome!

I occasionally found myself trying to write PHP that would write my PHP. Or I wanted to make it way too dynamic. I think these are common signs that you are making it more complicated than it needs to be. There is usually a rather simple elegant solution; it’s sometimes hard to see it, so you may need to take a break if you’re stuck.

PHP Today

PHP has come a long way. It has come further than I ever imagined it would. Don’t take that as a poke against PHP; it felt as if it slowed down a little bit for a little while, but it has picked up the pace.

A lot of the sites I work on that are in production are running PHP 5.6, some are running PHP 7.0, and some are running PHP 7.1. There haven’t been very many functions deprecated in the new versions, but it can still be difficult to upgrade all your sites to the latest version. While anything may be possible, not everything is feasible or ideal.

The community has pulled together to improve every aspect of this beautiful language. We have some great frameworks, package management, and some helpful resources for learning. I imagine more things are to come, and I’m excited to see what they are.

Conclusion

Covering CompuServe and Juno brought back some memories. We had CompuServe as our ISP, and we would use Juno for email. We would dial into BBS’s (Bulletin Board Systems) and send each other messages or play games. In my lifetime we have gone from 56K dial-up modems to gigabit internet at home. To give you a better idea, 56K would download at 56,000 bits per second and gigabit internet will download at 1,000,000,000 bits per second.

I’ve learned other programming languages along my journey, and I encourage you to do the same once you feel comfortable with one. While learning another language, it helped me change the way I think and improved my overall programming skills.

I’ve had a couple of programming mentors while I was learning to program and it helped, but it can also hold you back. If you don’t try, and immediately ask for help, you won’t learn as fast as you can. Don’t rush, make mistakes, and learn from those mistakes.

Of course, if you need help, please feel free to email me. I’ll do my best to help you.

Dependency Injection

Dependency Injection

How does dependency injection work? Is it magic? Does it hurt? The first two questions might be reasonable, and the third one might be something I would ask. Either way, I’ll cover these issues and more.

Hopefully, you will agree that this is one of the easier design patterns to understand and implement. When I speak of design patterns, I’m not referring to the sewing patterns your mom used to make your clothes as a kid. These design patterns should help you overcome everyday programming tasks. They have been around for awhile and utilized by some brilliant programmers.

Why Use Dependency Injection

You may instantiate concrete classes inside of your other classes all loosey goosey like a wild developer. If you do, then I hope you keep reading, because I have some tips for you.

When you use concrete classes instead of interfaces, you are only making your life harder. Or you’re making someone else’s life harder, either way, stop it. If your code looks like the example below, then you know who you are.


<?php
class Notification {
	// . . .
	public function send($message) {
		$emailer = new ThirdPartyEmailer;
		$emailer->sendMessage('[email protected]', $message);
	}
	// . . .
}

As you can see from the example above, you lock yourself into using that one class. Doing this will prevent the ease of future growth of the application.

How To Use Dependency Injection

While it may be too late for some of you or some of your applications, it isn’t too late to learn a better way to do things. If you code your classes to an interface, you are already on the right track, and I applaud you. If you aren’t sure about interfaces, then I suggest you read my post about Interfaces in PHP.

Instead of instantiating a new concrete class in your method, have that methods class construct accept a parameter type of the interface your concrete class implements. Since that is a mouthful and sounds confusing, I think if you look at the example below, you’ll see what I mean.


<?php
interface EmailerContract {
	public function sendMessage($toEmail, $message);
}
class ThirdPartyEmailer implements EmailerContract {
	// . . .
	public function sendMessage($toEmail, $message) {
		// send email code
	}
	// . . .
}
class NewEmailer implements EmailerContract {
	// . . .
	public function sendMessage($toEmail, $message) {
		// send email code
	}
	// . . .
}
class Notification {
	private $emailer;
	public function __construct(EmailerContract $emailer) {
		$this->emailer = $emailer;	
	}
	// . . .
	public function send($message) {
		$this->emailer->sendMessage('[email protected]', $message);
	}
	// . . .
}
$notifcation = new Notification(new ThirdPartyEmailer);
$notifcation->send('Welcome!');
// if we switched third party emailers down the road, we can easily switch it out
$notification = new Notification(new NewEmailer);
$notifcation->send('Welcome! We switched mailers.');

Since your concrete class implements that interface, it is a valid argument for that construct, and you can use it. And since it does implement that interface, you know what methods will be available.

Conclusion

You may already be using this design pattern, and you didn’t even know it. If you aren’t using it, I encourage you to do so, it isn’t a huge change, and I hope the concept is one you can grasp. Of course, if you don’t understand, send me an email, and I’ll be happy to help.

PHP Unit Testing

PHP Unit Testing

Unit testing can reduce the number of headaches you may have with a large project. You should test each “unit” or piece of code. While it may be difficult for 100% code coverage (testing everything), it should be something you aim to do. I’ll cover assertions, methods, doc blocks, and continuous integration.

If you add your tests as you code, you’ll have assurances that anything new you write won’t affect the code you previously wrote. If it does, then one of your previous tests should fail.

Assertions

An expression which, if false, indicates an error.

To make an assertion, you’ll need to have something to assert. If you have a method that multiplies integers by five, you know if you pass in three, you’ll get fifteen. So, that could be an assertion you test. When writing your methods, you’ll know what they are returning, and it it’s good practice to test it.

Methods

At the time of writing this, there are 48 assert methods in PHPUnit. Here is a list of assert methods that you may commonly use:

  • assertContains()
  • assertEmpty()
  • assertEquals()
  • assertFalse()
  • assertFileExists()
  • assertFileIsReadable()
  • assertFileIsWritable()
  • assertGreaterThan()
  • assertGreaterThanOrEqual()
  • assertInstanceOf()
  • assertInternalType()
  • assertJsonStringEqualsJsonFile()
  • assertNull()
  • assertSame()
  • assertTrue()

The above list should be enough to get you started. The PHPUnit manual will always have an up-to-date list you will reference.

Annotations

An annotation is a neat little way to add some additional assertions to your code. If you’re familiar with documentation blocks (doc blocks), then I hope these will look familiar. They must start with “/**” and end with “*/.” The annotation begins with a “@” sign immediately follow by the assertion you wish to use. One of the ones I use a lot is the “@expectedException,” which if an exception is triggered, this will catch it and the test will pass.

Example

In this example, we are testing the add method of the Calculator class, as we should test every method of each class. Testing each unit of code is important.


<?php

class Calculator
{
	public static function add($firstNumber, $secondNumber)
	{
		return $firstNumber + $secondNumber;
	}
	// . . .
}

class CalculatorTest extends PHPUnit_Framework_TestCase
{
	public function testAdd()
	{
		$sum = Calculator::add(40, 60);
		$this->assertEquals($sum, 100);
	}
}

Since we know that 60 plus 40 equals 100, we can assert that the $sum will be equal to 100. Granted this is an elementary example, I hope it helps you understand how, why, and what a unit test is.

Tips

Your tests should not need a network connection or require on anything else other than your code. Use Mock objects when you need to “pretend” to do things. In my PHP DigitalOcean API client, I don’t want to create/delete/resize a Droplet every time I run my tests; that would cost me money.

Continous Integration

Your tests may pass on your local machine, but what if someone wants to use it running a different version of PHP? If someone pulls your code down to a new server, will it work as it should? There are a lot of reasons to incorporate continuous integration into your workflow, but I won’t try to cover them all.

I am a fan of Travis-CI as they provide free unit testing for your open source repositories. I currently test on PHP 5.6 and up, which includes the nightly build, this helps ensure my code will continue to work on later releases of PHP. You will need to add a .travis-ci.yml file to your code and can reference my Travis-CI file to get started.

If all your tests pass, then you can have your code automatically deploy to your live website or application. Hopefully, you will write enough tests to ensure it doesn’t crash.

Conclusion

Unit Testing may sound like a big leap for someone just beginning, but you will thank yourself later if you start now. You should commit frequently, test everything, and keep practicing.

More importantly, find your way of doing things, a way you’re comfortable with, that you understand. Do what makes you happy as long as you aren’t hurting others, and you will succeed.

Grasping these concepts can be difficult on your own, so if you ever have questions or need help, send me an email. Reference the PHPUnit book if you like raw documentation.

Gulp and SCSS

Gulp and SCSS

There are so many technologies out there that you can learn; it’s probably impossible to keep up with all of them. It’s still fun to try and learn a little bit about a lot of things. Perhaps we should focus on what we are good at and dabble in everything else. I recently decided to play with gulp, and I like what I saw.

In order to use gulp, you will need to install a few things, and they are listed below.

  • nodejs
  • npm (I’ll talk about yarn in another post)
  • gulp

First, you’ll need to install nodejs and can follow this tutorial. The node package manager (npm) should come with nodejs. Then you will need to install gulp by running “npm install –global gulp-cli.”

Now that you have the required packages installed, you can clone my gulplol repository. My “gulpfile.js” is configured to look for Sassy CSS files in the “scss” folder. You can run “gulp styles” to run it once or “gulp” to have it listen for changes. If it looks for changes, any time you save, it will compile your SCSS. It will also auto prefix certain non-standard CSS properties. It will minify the CSS and also add a source map to view the minified files easier.

Feel free to email me if you have any questions.

PHP Type Hinting

PHP Type Hinting

PHP type hinting is something I’m a huge fan of and think everyone should use. It removes a lot of the guess work from your PHP; you know that your method will only accept certain types. Being able to know this in advance will help reduce unexpected errors.

PHP’s Basic Types

Scalar Types

A scalar type holds a single value.

  • bool
  • int
  • float
  • string

Compound Types

A compound type may contain multiple values. Below are the compound types that PHP supports.

  • array
  • callable
  • class/interface name

Example of Scalar/Compound Types

Below is an example of type hinting your methods; I’ve added comments to help explain.


<?php
class Book {
    public function read(int $numberOfPages)
    {
        // You don't want someone passing 'dog' as a parameter
        // 'You're going to read dog pages' doesn't make sense.
        echo "You're going to read " . $numberOfPages . " pages";
    }

    public function flipPages(array $pages)
    {
        // When you know you're getting an array, it helps!
        foreach($pages as $page)
        {
            echo $page;
        }
    }
}

Type hinting keeps you from having to use functions like is_int to ensure your method is receiving the correct type.

PHP Object Oriented Types

When you’re learning to write object oriented PHP, it can be a bit difficult to grasp the concept and understand the benefits. I encourage you to write/use classes whenever you can, instead of using procedural code. If you keep practicing, you’ll get better, and eventually become a more efficient developer. Below is an example of using a concrete class as a type hint.

Type Hint with Concrete Class


<?php
interface GymEquipment {
    public function get();
}

class Weight implements GymEquipment {
    protected $lbs;

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

    public function get()
    {
        echo "I'm getting " . $this->lbs . "lbs of weights";
    }
}

class RowingMachine implements GymEquipment {
    protected $difficulty;

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

    public function get()
    {
        echo "I'm going to row so " . $this->difficulty;
    }
}

class Exercise {
    public function lift(Weight $weight)
    {
        $weight->get();
    }

    public function row(RowingMachine $rowingMachine)
    {
        $rowingMachine->get();
    }
}

$exercise = new Exercise;

$weight = new Weight(45);
$exercise->lift($weight); // OUTPUT: I'm getting 45lbs of weights

$rowingMachine = new RowingMachine('hard');
$exercise->row($rowingMachine); // OUTPUT: I'm going to row so hard

Our Weight class expects an integer since lbs is a standard measurement. The RowingMachine class expects a string since I have no idea what kind of settings one may have.

The Exercise class has two methods, lift() and row(). Unless you’re really strong, I don’t think you want to lift the rowing machine, so lift() only accepts the type Weight. If lift() accepted the interface GymEquipment then it could accept a RowingMachine as an argument. The row() method of the Exercise class only accepts a type of RowingMachine.

Type Hint with Interface

Let’s see how we would type hint using an interface. We will need to refactor our code a little bit, and it will usually benefit us by doing this.


<?php
interface GymEquipment {
    public function start();
    public function stop();
}

class Weight implements GymEquipment {
    protected $weight;
    public function __construct(int $weight)
    {
        $this->weight = $weight;
    }
    public function start()
    {
        echo "I'm getting " . $this->weight . "lbs of weights";
    }
    public function stop()
    {
        echo "I'm done lifting weights.";
    }
}

class RowingMachine implements GymEquipment {
    protected $difficulty;
    public function __construct(string $difficulty)
    {
        $this->difficulty = $difficulty;
    }
    public function start()
    {
        echo "I'm going to row so " . $this->difficulty;
    }
    public function stop()
    {
        echo "I'm done rowing.";
    }
}

class Exercise {
    public function begin(GymEquipment $gymEquipment)
    {
        $gymEquipment->start();
    }
    public function end(GymEquipment $gymEquipment)
    {
        $gymEquipment->stop();
    }
}

$exercise = new Exercise;

$weight = new Weight(45);
$exercise->begin($weight); // OUTPUT: I'm getting 45lbs of weights
$exercise->end($weight); // OUTPUT: I'm done lifting weights.

$rowingMachine = new RowingMachine('hard');
$exercise->begin($rowingMachine); // OUTPUT: I'm going to row so hard
$exercise->end($rowingMachine); // OUTPUT: I'm done rowing.

By using an interface as a type hint, we can pass multiple concrete classes as a parameter, as long as the class implements the interface. By doing this, you aren’t restricting yourself.

Conclusion

If you would like to practice object-oriented PHP on your own, try writing the Exercise example that also accepts a name. Then, when it echo’s out the action, have it include a name from the Exercise construct. If you want to write something else, then do that, do what interests you. Put your code on GitHub and email it to me; also email me if you have any questions.

Creating a PHP Package

Creating a PHP Package

Make sure you have composer installed if you want to use PHP packages.

If you’re new to PHP, then you may not know what a package is or why they’re nice. If you played with Legos as a kid, think about those blocks, they came in different shapes, sizes, and colors. Each had a purpose and was useful, maybe you didn’t always need them all, but you had them. Instead of writing all the PHP for your project, someone may have already written a few pieces, and you could use those with your code. The people who write packages usually spend lots of time testing them, to ensure they work properly in any circumstance. It would be impossible to write and test every aspect of your program as much as it would be if you used packages.

Perhaps you find yourself using some PHP you’ve written, over and over again; which is a good practice, but it can become time-consuming when you make it better and then have to update it everywhere else you used it. Creating your package would be a great solution to your dilemma. I recommend you follow semantic versioning, which will help prevent anything from breaking when you do an update.

Hopefully, you’re ready to get started, or maybe you already were. For this example, I’ll be using GitHub to host the repository, even though you may use other services. I’m going to assume you’re familiar with Git and GitHub, so go ahead and create a repo for this project.

For this example, we will be creating a package that replaces var_dump(). The PHP is simple and kind of pointless; however, it is useful for this post. Here is a list of the files you’ll need to create:

  • composer.json
  • src/Dump.php
  • src/ShowDumpContract.php
  • src/ShowDump.php

Our composer.json will look like this:


{
  "name": "levilol/dump",
  "description": "",
  "version": "1.0.0",
  "license": "MIT",
  "keywords": [""],
  "autoload": {
    "psr-4": {
      "levilol\": "src/"
    },
    "files": [ "src/Dump.php" ]
  },
  "require": {
    "php": ">=5.6"
  }
}

The name is important, it needs to be unique, it can usually mirror your repo username/project. Having a good description will help people find your package, the same goes for keywords. You should follow semantic versioning when releasing new versions; I suggest you start with 0.1.0 and move up as fast as you want. The license is up to you, for this example, I chose the MIT license. Autoload is where some of the magic starts to happen; PSR-4 saves you from having to include every file. The autoloader will include the file when you instantiate a class. We also want to include at least one file every time the program runs, whether it’s called or not, it will be loaded. Require can contain PHP versions, extensions, and other packages.

Our Dump file will declare a function and call the static method dump() in the ShowDump class. This function accepts a parameter of any type and passes that to our method.


<?php
use levilolShowDump;
function dump($var)
{
    foreach (func_get_args() as $var) {
        ShowDump::dump($var);
    }
}

I’ve always been told to code to an interface, so here is the interface for the ShowDump class. It has one method that accepts one parameter.


<?php
namespace levilol;
interface ShowDumpContract
{
    public static function dump($data);
}

Now it’s time for the meat and potatoes of this package. The dump() method is static, so you don’t have to instantiate the class, which we don’t need to do anyway since we have the dump() function. This method checks to see if you’re calling it from the command line interface and if you are, it calls the regular var_dump() and if you aren’t, it wraps the var_dump() in pre tags.


<?php
namespace levilol;
class ShowDump implements ShowDumpContract
{
    public static function dump($data)
    {
        if (PHP_SAPI == 'cli') {
            var_dump($data);
            return;
        }
        echo '<pre>';
        var_dump($data);
        echo '</pre>';
    }
}

You’re welcome to reference my example repo on GitHub. It has a few more files, such as tests and an README.md, which aren’t required.

Now you’ll need to head over to Packagist, sign in with your GitHub account, and submit your package. People can then require your package in two ways, via their composer.json or from the command line by typing composer require levilol/dump. The latter will add it to your composer.json file.

Please email me if something wasn’t clear or if you’re having trouble.

Factory Design Pattern

Factory Design Pattern

In this post, I’m going to talk about a design pattern; a design pattern is something you can use to solve common problems. I’m going to cover a simple example of the “factory design pattern” and an example that is a little more complicated in another post. This concept may be a bit difficult to wrap your mind around, but it’s worth it in the end.

For the simple example, we will pretend we are developing an e-commerce solution for a t-shirt we designed. We designed and printed this awesome shirt; our friends love it, and we are going to sell a ton. We will start off with our AwesomeShirt class.


<?php
class AwesomeShirt {
    public function order() {
        echo 'Awesome shirt order placed.';
    }

    public function ship() {
        echo 'Awesome shirt order shipped.';
    }

    public function returnOrder() {
        echo 'Awesome shirt order returned.';
    }
}

Okay, that’ll work, but what if we become successful and people want us to make some different shirts? Let’s rethink this and refactor.


<?php
class ShirtFactory {
    public static function build($shirtType = null) {
        if($shirtType == null) {
            throw new Exception('Must Pass a Shirt Type.');
        }

        $shirtClass = ucfirst($shirtType) . 'Shirt';

        if(class_exists($shirtClass)) {
            return new $shirtClass;
        }

        throw new Exception('Invalid Shirt Type.');
    }
}

interface ShirtType {
    public function order();
    public function ship();
    public function returnOrder();
}

class AwesomeShirt implements ShirtType {
    public function order() {
        echo 'Awesome shirt order placed.';
    }

    public function ship() {
        echo 'Awesome shirt order shipped.';
    }

    public function returnOrder() {
        echo 'Awesome shirt order returned.';
    }
}

class FunnyShirt implements ShirtType {
    public function order() {
        echo 'Funny shirt order placed.';
    }

    public function ship() {
        echo 'Funny shirt order shipped.';
    }

    public function returnOrder() {
        echo 'Funny shirt order returned.';
    }
}

$shirt = ShirtFactory::build('Awesome');
$shirt->order(); // OUTPUT: Awesome shirt order placed.

Okay, what happened? Well, we created a ShirtFactory class that can build() different kinds of shirts.

We then created two types of shirts that implemented the ShirtType interface, which allows us to pass those to our factory method build. If we ever need to make any more types of shirts, we can.

Do you see anything that we’ve repeated and could maybe simplify? Well, all shirts can be ordered, shipped, and returned. Each of those methods echoes out the name and the action. Let’s create an abstract class to handle the work for us.


<?php
interface ShirtType {
    public function order();
    public function ship();
    public function returnOrder();
}

abstract class Products implements ShirtType {
    protected $name;

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

    public function order() {
        echo $this->name . ' shirt order placed.';
    }

    public function ship() {
        echo $this->name . ' shirt order shipped.';
    }

    public function returnOrder() {
        echo $this->name . ' shirt order returned.';
    }
}

class AwesomeShirt extends Products implements ShirtType {
    
}

class FunnyShirt extends Products implements ShirtType {
    
}

class ShirtFactory {
    public static function build($shirtType = null) {
        if($shirtType == null) {
            throw new Exception('Must Pass a Shirt Type.');
        }

        $shirtClass = ucfirst($shirtType) . 'Shirt';

        if(class_exists($shirtClass)) {
            return new $shirtClass($shirtType);
        }

        throw new Exception('Invalid Shirt Type.');
    }
}

$shirt = ShirtFactory::build('Awesome');
$shirt->order(); // OUTPUT: Awesome shirt order placed.

So, what did we do? Well, we removed the methods from the concrete classes AwesomeShirt and FunnyShirt and put them in our abstract class Product. When we use the build() method in the ShirtFactory class, we instantiate the class for that shirt and pass the name of it to the construct, which then sets the $name property. When we run ShirtFactory::build('Awesome'); it returns a new AwesomeShirt. We are then able to call the different methods for that class, such as order() as I did in the example above.

In the next post about this design pattern, I’ll use reflection to do some really neat things. PHP has come a long way since I first started writing it and I feel like more great things are to come. If you have any questions, comments, or corrections; please email me. I’m happy to help others learn.

If none of it made any sense; take a nap and try again later. If you read it again and still don’t understand, it’s okay, don’t get frustrated. I’ll keep writing more posts, and you’ll learn it one day. Keep reading and practicing.

Intro to OO PHP

Intro to OO PHP

To learn how to write Object Oriented PHP, we will start with some basics and build upon those. I will use fictitious and realistic examples. We will also use a simple autoloader, so we don’t have to use includes for each file.

Autoloading


<?php
/**
* autoload.php
*/
function __autoload($class_name) {
	require_once("./src/$class_name.php");
}

Eventually, you will want to use composer to install packages and to generate your autoloader.

Classes

Interfaces

Abstract Classes

Traits

Polymorphism

Namespaces

Top 5 PHP Frameworks

Top 5 PHP Frameworks

In this post, I’ll review what I believe to be the top five PHP frameworks. These frameworks are in no particular order since they all have benefits and can be handy in different situations. Also, this is a matter of opinion; I urge you to try them out. Even try ones I don’t have listed. Heck, write your own.

Silex

I’ll start with Silex since that is what I used for this site. SensioLabs makes this micro-framework, and they put out some excellent packages. They’ve done a great job of making money by certifying developers. I think their primary goal is to write great PHP.

This website is pretty simple; you might call it a “basic b*%$h.” It has a couple of static pages and pulls the blog entries from a database. It handles the routing and uses the twig template engine. Since the templates get compiled, it’s fast. I’m using Doctrine to manage the database queries; which simplifies things.

I’ll recommend Silex for small applications; like this blog.

Slim Framework

Since I talked about Silex, a micro-framework, I’ll talk about Slim since it falls in the same category. Slim is great, but after looking at the code, I feel like Silex is stronger, so use caution when deciding. Slim is coming out with 4.0 shortly, and they may be changing some things.

I recently used Slim to develop an API for something I’m currently developing. I won’t go into too much detail because it’s top secret, but it is a RESTful API, using GET, PUT, POST, and DELETE (this always makes me think of the movie “Dodgeball”). It’s also using an SQLite database. The main reason I chose Slim for this project; was because it is small and fast. I was able to include a few other packages along with Slim to help me accomplish everything I need.

Don’t knock it until you try it; I like it for writing APIs.

Laravel

Okay, some people may wonder why I didn’t lead with Laravel. Laravel is magically delicious and does everything under the sun. Taylor Otwell (and contributors) has made a fantastic framework. It’s massive. It uses some Symfony packages because he knows a good library when he sees it. He is superb at keeping things consistent and provides well-defined names for things.

Laravel will do anything you need. It is great when making full blown web applications. It’s tested out the wazoo. It is one of the easier frameworks to learn. And it’s very popular right now. If you know PHP and haven’t heard it, you may want to get out from underneath that rock and take a look.

If you have a great idea for a web app, then you should try Laravel.

Symfony

Several frameworks that require Symfony components. I believe that is one of the highest forms of a compliment when other people and the community use your libraries. The Symfony framework certainly works well with the other Symfony components, which may give it an edge. However, those other frameworks chose not to use all of the components and write their own for a reason. I’m a huge fan of Composer and putting different packages together. The nodejs packages have gotten a little out of hand, and I hope PHP doesn’t head in that direction.

If you want to learn a framework and get a certified in it, check out Symfony. Or if you like the name, check it out.

Yii

Okay, I know what you’re thinking, but it’s not bad. CraftCMS was written using Yii, and I respect those dudes. It has a lot of features, relatively quick, and fairly secure. Yii has great documentation, which is sometimes hard to find. It can be used to build web apps and anything else you would want to make. In my opinion, it does have a steeper learning curve, but it may be worth it. It isn’t as popular as some of the other frameworks, but it is a contender.

Check out Yii if you want to be different. Little fun fact, it wasn’t created by Yahoo.

Conclusion

Sometimes when using a framework, I feel like I’m not doing anything anymore, all the heavy lifting is written by someone else. It can be a pleasant feeling and a sad feeling as I like to write the behind the scenes code. It helps speed up development time, which makes everyone happy. Ultimately, you should probably do whatever your boss says, but if you’re learning for fun, then do whatever you want!

If you disagree with anything, I don’t care; this is only my opinion. However, feel free to email me, and we can discuss it further. As always, if you have questions, also email me, I’m happy to help.