Tag: packagist

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.

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.

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.