Start a PHP project - the PSR way

Handwritten on 01 Dec 2017

Start a PHP project - the PSR way

First of all create a new directory:

mkdir MyApp
cd MyApp/

Now create a file:

touch composer.json

Add the following sample content to composer.json:

{
    "name": "MyApp",
    "description": "Provide a description for MyApp",
    "authors": [
        "adis@live.nl",
    ],
}

Now you can continue and require the php packages you need. For example, if you need the PHP Facebook SDK you would need to run the following command:

composer require facebook/graph-sdk

The composer require command will add the following to your composer.json file:

"require": {
    "facebook/graph-sdk": "^5.6"
}

Your composer.json file will look like:

{
    "name": "MyApp",
    "description": "Provide a description for MyApp",
    "authors": [
        "adis@live.nl",
    ],
    "require": {
        "facebook/graph-sdk": "^5.6"
    }
}

Our current directory structure looks like:

- MyApp
|-- composer.json
|-- src
|-- tests
|-- vendor

Now we need to define the namespace for our src folder. Most of the times our root directory represents our main package, in this case MyApp will become our main namespace. Let's define this in our composer.json:

{
    "name": "MyApp",
    "description": "Provide a description for MyApp",
    "authors": [
        "adis@live.nl",
    ],
    "require": {
        "facebook/graph-sdk": "^5.6"
    },
    "autoload": {
        "psr-4": {
            "MyApp\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "MyApp\\": "tests/"
        }
    }
}

In this example our app is a trading app for books. So it would be logical to have a book class inside our src directory. This would mean that the Book class is inside the MyApp namespace. Our Book class will look like:

<?php

namespace MyApp;

/**
 * Represents a simple book
 */
class Book {

    /**
     * @var string|null
     */
    protected $title;
    /**
     * @var string
     */
    protected $isbn;
    /**
     * @var MyApp\Author
     */
    protected $author;

}

Now the directory structure looks like:

- MyApp
|-- composer.json
|-- src
    |-- Book.php
|-- tests
|-- vendor

Remember to regenerate the autoload classes when you add new php files to your project: composer dump.

If you add a bootstrap.php, this would be a starting point for your application. This bootstrap.php should at least contain the autoload file:

// autoload 
require __DIR__ . '/vendor/autoload.php';

// now you can bootstrap your application
$myApp = new MyApp\Book();

Further reading?

And I you want to do some serious PHP coding you should read PHP The right way.

Happy writing code!

php composer

Logo Adis.me

© 2024 Handcrafted in Nijmegen, The Netherlands