Category: PHP

Advanced PHP is Actually Simple – Learn How Today

Advanced PHP is Actually Simple – Learn How Today

Advanced PHP methods, practices, processes, and everything else can be a bit daunting. If you find it hard to understand some of the documentation or tutorials out there, don’t worry, I can help! I struggled to learn some of the core concepts, but eventually figured it out, I hope I can help you learn with less of a struggle. Having a good development environment is a huge step in the right direction. For work, I use a Windows machine and a MacBook Pro. At home, I have a desktop running FreeBSD. Use whatever you are most familiar.

Packages

You don’t have to do everything yourself; this was a hard lesson for me to learn. There are groups of people who focus on a single PHP package. That package is going to be well written, tested, and hopefully documented. I suggest you use PHP packages when you can. You can browse the available packages on packagist. You will need to have composer installed on your dev machine. If you have an idea for a package, then read my post on creating a PHP package.

Autoloader

The autoloader isn’t magic, but it is very helpful when writing advanced PHP. It will conditionally include the needed PHP files based on the code being run. No longer will you need to have dozens of includes as the autoloader will handle most of them for you. Packages have a registered namespace that tells the autoloader where their files so it can load them. This allows you to easily instantiate a new object without having to include the needed files.

PHP Design Patterns

You’re only making it harder for yourself if you aren’t using design patterns. There are plenty of definitions of design patterns, and none of them make sense. When a definition is defined with other complicated words, I find it confusing. Below is a simple explanation of design patterns.

A design pattern is a way of structuring your code so it can easily be extended, enhanced, or fixed. Most advanced PHP applications will use a couple of design patterns. They’ll help keep your code organized and understandable.

I have written a few posts on different design patterns, such as the adapter pattern, dependency injection, and the factory design pattern. “Design Patterns: Elements of Reusable Object-Oriented Software” by Erich Gamma is an amazing book if you want to learn even more.

Security

There have been a lot of very public data breaches in the last couple months, so I will also cover some basic security tips. Whether your application is used by a couple of people or hundreds, you should always practice safe security. If your app uses a database, an API, or some other type of service, it could be vulnerable.

When you are writing information to your database, please use PDO. PDO is faster and more secure. PDO Tutorial does an excellent job of explaining everything clearly and concisely. Feel free to ask any questions in the comments below.

Another important aspect of application security is protecting against CSRF (Cross-Site Request Forgery). If I were to create an HTML form on my website and set the POST parameter to your website, how would your website know where the post came from? It’s a very difficult thing to do unless you use a CSRF token with your forms. When a user sees a form, you also generate a CSRF token. You add the CSRF token to a session variable and to a hidden input field that is part of the form. Then when the user submits the form, you can check the hidden input field data against the session variable. If they match, then you know they submitted the form from your site.

Visit the OWASP website if you would like to learn more about security.

Advanced PHP Conclusion

Programming is all about solving problems. We take a big problem, break it into smaller problems, solve the smaller ones first, and then we’ve solved the big problem. Keep trying to make your code smaller, simple, and elegant. Programming is art for logical people like yourself. Keep being curious. Let me know in the comments below if you have any questions. I would love to help.

Silex

Silex

This year I’ve continued to try different PHP frameworks. The ones I’ve tried are well written and have a fantastic community. I can see how some people may need to rely on a framework that does everything, but I like having control. And I prefer to add things instead of removing them.

Silex has been enjoyable to use while building web applications. I have a skeleton repo that has everything I need. This repo has webpack for SCSS, JS, and injecting assets into HTML. The folder structure is organized and easy to understand. The organized code is easier to maintain and debug.

Development Environment

Development Environment

Setting up a development environment can be a pain. Sometimes it can be harder than writing the app. Some resources can help you develop faster, but you need to learn how to configure it for what you know, and it’s worth it in the long run.

Gulp is one of those tools that speed up your development, and I’ve been using it for a few months. Gulp is excellent, but Webpack seems to be better and more straightforward to configure. There are still a few other node packages that you will need, such as Babel if you want to write your JavaScript in ES6.

I would like to create a boilerplate for future projects. It would need to contain some automation for PHP, JavaScript, and SCSS. And it would need to be able to test each of those. I’ve started building this boilerplate a couple of times, but I keep starting over. Hopefully, I will finish it soon.

It is worth taking the time to learn about each tool; it’s advantages and disadvantages. Spending a little bit of time planning will save you more time later.

PHP Adapter Design Pattern – Learn How It Can Help You

PHP Adapter Design Pattern – Learn How It Can Help You

When I think of an adapter, I think of the three prong to two prong electrical outlet thing. It allows me to plug in an electrical device that has three prongs (one with a ground) into a two prong outlet that doesn’t have a ground. The interface of the outlet is two holes and the interface of the device it has three prongs, so we need an adapter to help us. The PHP adapter pattern utilizes this very concept.

PHP Adapter Example

I’m going to keep going with the electrical outlet idea. Hopefully, this makes a little bit of sense.


<?php

interface ProngInterface {
	public function __construct();
}

interface TwoProngInterface {
	public function __construct(ProngInterface $prongOne, ProngInterface $prongTwo);
	public function plugTwoIn();
}

interface ThreeProngInterface {
	public function __construct(ProngInterface $prongOne, ProngInterface $prongTwo, ProngInterface $prongThree);
}

class Prong implements ProngInterface {
	public $prong;
	public function __construct() {
		$this->prong = '|'; // that is a prong
	}
}

class TwoProng implements TwoProngInterface {
	public $prongOne;
	public $prongTwo;
	public function __construct(ProngInterface $prongOne, ProngInterface $prongTwo) {
		$this->prongOne = $prongOne;
		$this->prongTwo = $prongTwo;
	}

	public function plugTwoIn() {
		echo 'both plugged in.' . "n";
	}
}

class ElectricalOutlet {
	public function __construct(TwoProngInterface $twoProng) {
		echo $twoProng->prongOne->prong . ' ' . $twoProng->prongTwo->prong . "n";
		$twoProng->plugTwoIn();
	}
}

// Our TV *should* have a ground.
class Television implements ThreeProngInterface {
	public $prongOne;
	public $prongTwo;
	public $prongThree;
	public function __construct(ProngInterface $prongOne, ProngInterface $prongTwo, ProngInterface $prongThree) {
		$this->prongOne = $prongOne;
		$this->prongTwo = $prongTwo;
		$this->prongThree = $prongThree;
	}
}

// Here is where the magic happens.
class TwoProngAdapter {
	public $twoProng;
	public function __construct(ThreeProngInterface $threeProng) {
		$this->twoProng = new TwoProng($threeProng->prongOne, $threeProng->prongTwo);
	}
	public function get() {
		return $this->twoProng;
	}
}

$tv = new Television(new Prong, new Prong, new Prong);
// we use the TwoProngAdapter to shave off one of the TV's prongs.
$adapter = (new TwoProngAdapter($tv))->get();
// It'll now work in our two prong electrical outlet!
$outlet = new ElectricalOutlet($adapter);

// we can also plug our two prong toaster into the two prong outlet!
$toaster = new TwoProng(new Prong, new Prong);
$outlet = new ElectricalOutlet($toaster);

Explanation

If you’ve read my other posts, I hope you understand some of the above code. If you’re lost, at least read Classes in PHP and PHP Type Hinting, those should help a little bit.

In the example, the ElectricalOutlet only accepts a device that implements the TwoProngInterface. We really want to watch TV, but it implements the ThreeProngInterface, and we can’t plug it directly into the EletricalOutlet, poop. Now your mom is yelling at you, she really wants to watch Wheel of Fortune, but the TV still has no power.

Luckily, we developed an adapter! The TwoProngAdapter accepts a device that implements the ThreeProngInterface and then returns a TwoProngInterface object. We can now plug in our TV and watch Wheel of Fortune! Congrats! You saved the day and your mother still loves you.

Advice

Read through the code above and see if you can follow the logic in your head. It might help if you read it from top to bottom then bottom to top. If you’re still struggling with it, try typing it up yourself and maybe modify it a little. Learning takes time and you shouldn’t get upset if you don’t understand it right away. It sometimes takes me days, weeks, and sometimes months to understand a concept. Always take a break.

Conclusion

Feel free to comment below. Please comment below. Or email me? Someone has to need some help. If you do ask for help, please share with me all your code and not a sliver of it. I need to see everything that is happening. Sometimes your problem is outside the scope you are focused on.

For those of you who know me, the Wheel of Fortune story never happened, it was made up. I was always prepared.

Disclaimer

Don’t try plugging anything with three prongs into a two prong outlet. I don’t care if you do have an adapter, it is a bad idea. The third prong is for the ground, which can help protect your device from being ruined.

Relationship Models for PHP and MySQL

Relationship Models for PHP and MySQL

Want to be in a relationship with a model? If that has always been a dream of yours, then I might be able to help. I firmly believe if you read this blog post, you’ll be able to attract any person you desire. Intelligence is an aphrodisiac.

This post is really about how I developed my own model capable of handling relationships in a database. That said, it is probably going to get more technical and longer than my other posts.

I wanted to create my own model instead of using a pre-existing solution because I needed a very simple solution. You may use the argument, “don’t reinvent the wheel,” and I will usually agree with you, but not this time. My simple solution did get a little more complicated when I wanted to add another feature. I kept adding features until it could do nearly any type of query that I may find myself using. Reinventing is a method of teaching myself new concepts that I may not normally have discovered.

How I Started

I first created an abstract class that all other models would extend. I chose an abstract class so I could write the logic in the methods and so no one should be able to instantiate it. A model only needs to extend the abstract class to be able to do any CRUD query.

Looking up synonyms for “model” on Google, I found the word “Illustrative” and thought it sounded cool. The name of my base model is called Illustrative. Next, I created a Person class that extends Illustrative. I then started adding some simple methods to the Illustrative class and using them on the Person class. A basic query is a “SELECT” statement so I started with that. I had my database credentials hardcoded in my Illustrative class and created a method to retrieve all the rows from the table. Instead of hardcoding the table name, I decided to make it the plural form of the class name, so “SELECT * FROM persons” was the query that was getting run.

At this point, I hadn’t done anything that excited me so I had to keep going.

Static Methods

When using a static method, you don’t need to instantiate the class, which is the way I like to do it. It really comes down to preference, as do most things, so do what you like.

A newly instantiated class is returned when you call one of the static methods that the model inherits from Illustrative. This gets things started and allows you to use method chaining to build your entire query. Below are two examples of how it can be used for instantiating and method chaining.


$result = Person::fetch()->order('id', 'desc')->get();
$result = Person::fetch()->order('id', 'desc')->limit(1)->get();

As long as I thoroughly document all the methods and their parameters, this will help someone who isn’t familiar with SQL retrieve rows from the database. I think it is verbose enough to English vernacular to make it seem familiar.

Saving Records

While your program should probably read from the database more than it writes, it still needs to be able to create new rows. Assuming the Baller class extends the Illustrative class, you could do something like below.


$p = new Baller;
$p->name = 'alex';
$p->save();

This allows you to dynamically assign new properties to the class and then run the save method to add the new row. Some people aren’t a fan of dynamically adding properties, so I made another way to do it. The other way is shown below.


Baller::insert(['name' => 'levi']);

In case you are wondering, yes, Alex and I are ballers.

Finding Certain Rows

At first, I retrieved all the rows from the database and filtered the results based on the parameters. I knew this wasn’t a good way to do it, but I did it anyway. I later went back and corrected it. It now uses SQL to limit the results from the database.


$rows = User::fetch()->where(['name', '=', 'levi'])->get();

The example above is using the User model and running the static method fetch. By that, I hope you can deduce we are fetching a user. Instead of getting all of the users, we specify the where the method and pass an array to it. In that example, we are looking in the name field that is equal to “levi.”

While most of your queries may be simple, sometimes you have normalized your database and need to get information from multiple tables. I was a bit hesitant to move onto defining relationships, but I did, and I believe that is what makes this package useful.

Relationships

Writing a query that includes a JOIN isn’t very difficult, but writing a method in PHP to accomplish this was a little challenging. I’ve used frameworks that can handle this, but I’ve never tried to figure out how they do it. I dug into some code written by others and I turned up with nothing.

I eventually got the logic worked out, but my query results weren’t matching what I expected. I was getting a little frustrated, so I decided to sleep on it and let my diffused mode thinking take over. I woke up the next day with a fresh outlook on the project and found my mistake. I also redid some of the logic of the other methods.


$r = Post::fetch()->users()->where(['name', '=', 'levi'])->get();
var_dump($r);

Conclusion

I am not claiming to be intelligent. My opening paragraphs are usually my attempt at humor, and as poorly done as they may be, I don’t think I’m going to stop.

You can’t force yourself to see what is wrong. Take a break. Go for a walk, take a nap, talk to a friend, or do something other than work on that project. You could also switch to another project. Doing these things allows your brain to go into the diffused mode and work on the problem. Even though you aren’t actively thinking about it, your brain is looking at the problem from a wider perspective. That doesn’t mean your brain stopped.

I still need to add an update method, but you can check out the Illustrative repo.

Interface or Abstract Class

Interface or Abstract Class

I was recently working on a project, and I found myself adding the @property DocBlock to an interface. I knew it wasn’t good practice, but the class that is implementing that interface will provide those properties. I tried to convince myself it was okay.

Interface

Yes, it is a good idea to have your concrete classes implement an interface. It helps you plan how the class should work. Another benefit is using the interface as a type hint, you can then pass your concrete class as the parameter. This also allows someone to create their own implementation of the interface and pass it as a parameter.

An interface is essentially a signature. It can’t really do anything except provide a skeleton of what the class has to implement. You can’t declare properties, you can’t write any logic, and it can’t cook you breakfast. Although it can’t do much, you’ll usually use an interface instead of an abstract class.

Since an interface can’t define properties, what I was doing, was wrong. There was no agreement between the interface and the concrete class that said it must implement those properties. It is undefined behavior and would cause headaches down the road.

Example


<?php

interface CreateDropletRequestContract {
	public function __construct($name, $region, $size, $image);
}

class CreateDropletRequest implements CreateDropletRequestContract {
	// . . .
	private $name;
	private $region;
	private $size;
	private $image;

	public function __construct($name, $region, $size, $image) {
		$this->name = $name;
		$this->region = $region;
		$this->size = $size;
		$this->image = $image;
	}
	// . . .
}

Abstract Class

An abstract class can not be instantiated. With an abstract class, you don’t implement it, you extend it. Since the abstract class can provide logic, you must extend it to keep the logic. When you implement something, that means you are going to write the logic for it. Abstract classes can also define properties, which was I needed to do for my project.

A concrete class can only extend one class, but it can implement many interfaces. So when you are thinking everything out, try to plan ahead, even if it’s hard or you end up being wrong. The more you plan, the better you’ll get at doing it, and the easier it will become.

Example


<?php

abstract class CreateDropletRequestContract {
	private $name;
	private $region;
	private $size;
	private $image;

	public function __construct($name, $region, $size, $image) {
		$this->name = $name;
		$this->region = $region;
		$this->size = $size;
		$this->image = $image;
	}
}

class CreateDropletRequest extends CreateDropletRequestContract {
	// . . .
	// Most of the code could already be written in the abstract class.
	// . . .
}

Conclusion

I might ditch the abstract class and only implement the concrete class since it is only a data transfer object without an interface. Feel free to send me an email if you have any questions.

Example


<?php

class CreateDropletRequest extends RequestContract {
	// . . .
	private $name;
	private $region;
	private $size;
	private $image;

	public function __construct($name, $region, $size, $image) {
		$this->name = $name;
		$this->region = $region;
		$this->size = $size;
		$this->image = $image;
	}
	// . . .
}
Perceptual Hashing

Perceptual Hashing

Disclaimer: This is not a post about how you can get high and see things in a new light. Or is it?

You may assume that computers know everything and they don’t need people to do anything. We have assistants on our phones that we can talk to and ask questions, so who cares about how things actually work. Well, I do care, and I think this is pretty nifty.

I was recently tasked with writing a program to find duplicate images. I thought, no big deal, I’ll use a cryptographic hash and find the duplicates that way. And that way would work, but what about images that are similar to each other? Unfortunately using a cryptographic hash, like MD5 or SHA512, wouldn’t help you. The cryptographic hash algorithms use a waterfall effect to make the result completely different when only a few bits are changed in the source file.

After a little bit of research, I decided to use perceptual hashing.

What is Perceptual Hashing?

A perceptual hash is made up of a sample of the data from the original file. If you were to examine two pictures like you would read a book (from the top down and left to right), stopping every inch and recording the color; you would be creating a perceptual hash for that image. To keep it short, let’s say you end up with:

  • Blue
  • Blue
  • Blue
  • Yellow
  • Green
  • Green

Then if we examined another picture that is similar to the first, we might get:

  • Blue
  • Blue
  • Blue
  • Yellow
  • Orange
  • Green

As an intelligent human person, you can obviously tell they are similar. Now you can also use a systematic way to tell they’re similar since you can say there is only one color different. Of course, actual pictures are made up of a lot more pixels and colors.

Hamming Distance

Just how similar are they? Are they close? Are they the same? How would you measure the similarity? Well, you can use the Hamming distance. You would first XOR the two perceptual hashes; then you would count the number of ones in that binary string. That will give you the Hamming distance. Some people may say the Levenshtein distance would work better, but I’ll disagree. I’m not going to put an example of finding the Hamming distance on here because I don’t want to get too technical in this post.

Conclusion

These explanations may not be 100% accurate, but it is how I decided to explain them. I feel as if they accurately represent the underlying foundation of the concepts. If you would like to see how to measure the Hamming distance, send me an email, and I’ll send you some code I wrote along with an explanation. I’m okay if you want to create a new email address and pretend to be someone else ;).

I went ahead and wrote a function in C that finds the Hamming distance and I put it in a Github Gist. I’m not sure it is working correctly, so don’t use it for anything in production. I have PHP version that is working if you would like to see it.

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.