Building A Zend Framework 2 Application - Hello World Part 1

Building A Zend Framework 2 Application - Hello World Part 1

So in my last atricle we installed the Zend Framework on Ubuntu Server, now we will use this knowledge to make our first ZF2 app called 'Hello World'. Not inspiring I know but it will help us to hit the ground running (so to speak).

Now down to work, first fire up the terminal window and change the directory to the project one we created in 'Installing Zend Framework'. Now we should have a directory structure like:

zf2-tutorial
|--vendor
| |--autoload.php
| |--bin
| |--composer
| |--zendframework
|--composer.json
|--composer.lock

The 'vendor' directory will house all our php libraries like Zend Framework so we don't need to worry about that for now. We will need to add a few directories and files so the directory structure should look like (don't worry about creating them now we will do this as we go):

zf2-tutorial
|--config
|  |--aplication.config.php
|  |--autoload
|     |--global.php
|--module
|  |--Application
|     |--config
|     |  |--module.config.php
|     |--src
|     |  |--Application
|     |     |--Controller
|     |        |--IndexController.php
|     |--view
|     |  |--application
|     |     |--index
|     |     |  |-index.phtml
|     |     |--error
|     |     |  |--404.phtml
|     |     |  |--index.phtml
|     |     |--layout
|     |     |  |--layout.phtml
|     |--autoload_classmap.php
|     |--Module.php
|--public
|  |--.htaccess
|  |--index.php
|  |--css
|  |--js
|  |--img
|--vendor
|  |--autoload.php
|  |--bin
|  |--composer
|  |--zendframework
|--composer.json
|--composer.lock

So to start change directory to the tutorial on by

cd ~/public/zf2-tutorial

First we make the public directory

mkdir public

Now we make two files, one at a time in this directory, first one '.htaccess' so

nano public/.htaccess

then add this

RewriteEngine On

# The following rule tells Apache that if the requested filename
# exists, simply serve it.
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]

# The following rewrites all other queries to index.php. The
# condition ensures that if you are using Apache aliases to do
# mass virtual hosting, the base path will be prepended to
# allow proper resolution of the index.php file; it will work
# in non-aliased environments as well, providing a safe, one-size
# fits all solution.
RewriteCond %{REQUEST_URI}::$1 ^(/.+)(.+)::\2$
RewriteRule ^(.*) - [E=BASE:%1]
RewriteRule ^(.*)$ %{ENV:BASE}index.php [NC,L]

then press Ctrl O and then Ctrl X to exit the editor. The code in this file tells apache web server to redirect all requests to index.php as long as the requested filename does not exist else it will serve it. Now we create the index.php file and add our code to it, so

nano public/index.php

and the add this code

<?php

// If we're running under `php -S` with PHP 5.4.0+
// Thanks to Stephan Sokolow
if (php_sapi_name() == 'cli-server') {

    // Replicate the effects of basic "index.php"-hiding mod_rewrite rules
    $_SERVER['SCRIPT_NAME'] = str_replace(__DIR__, '', __FILE__);
    $_SERVER['SCRIPT_FILENAME'] = __FILE__;

    // Replicate the .htaccess "serve existing files" bit
    $url_parts = parse_url($_SERVER["REQUEST_URI"]);

    $_req = rtrim($_SERVER['DOCUMENT_ROOT'] . $url_parts['path'], '/' . DIRECTORY_SEPARATOR);

    if (__FILE__ !== $_req && __DIR__ !== $_req && file_exists($_req)) {
        return false; // serve the requested resource as-is.
    }
}

/**
 * This makes our life easier when dealing with paths. Everything is relative
 * to the application root now.
 */
chdir(dirname(__DIR__));

define('APPLICATION_PATH', dirname(__DIR__));

// Setup autoloading
if (file_exists('vendor/autoload.php')) {
    $loader = include 'vendor/autoload.php';
}

if (!class_exists('Zend\Loader\AutoloaderFactory')) {
    throw new RuntimeException('Unable to load ZF2. Run `php composer.phar install` or define a ZF2_PATH environment variable.');
}

$config = require 'config/application.config.php';

// Run the application!
Zend\Mvc\Application::init($config)->run();

press Ctrl O and then Ctrl X to exit the editor.

OK so what's happening here is lines 5-19 just initiates the .htaccess file if we are using the build-in web server that ships with php 5.4 (which we will use to test our app).

Line 25: here we change the directory to be the one above the public folder so everything all files are relative to our app root

Line 27: redefine a global constant 'APPLICATION_PATH' which will the app root as an absolute path.

Line 30-32: sets up are autoloading so we don't have to add require_once('some_php_file.php'); to our php class files.

Line 34-36: checks whether we can load the Zend Framework, if not then we throw an exception

Line 38: we include then application config file and assign it to a variable called $config

Line 41: we now tell the MVC in Zend Framework to run the app using the config file.

So with that we now need to code the config file. so in the terminal again we make the needed directories

mkdir -p config/autoload

then we make a config file like so

nano config/application.config.php

and add this to it:

<?php

return [
    'modules' => [
        'Application',
    ],
    'module_listener_options' => [
        'module_paths' => [
            './vendor',
            './module',
        ],
        'config_glob_paths' => [
            'config/autoload/{,*.}{global,local}.php',
        ],
    ],
];

press Ctrl O and then Ctrl X to exit the editor

here we create an array tell which modules to load, as we will have only one for now we use 'Application' (we will create this module shortly) then we setup the module paths which will live in either the module folder or the vendor folder and that's all we need for now and to load any config overrides in the autoload folder. You may of noticed that I am using a funny array syntax which as of php 5.4 we can use [] instead of array() for array creation.

Now we create a global override config file in the autoload folder so

nano config/autoload/global.php

and in this file we just return an empty array for now.

<?php

return [
];

press Ctrl O and then Ctrl X to exit the editor. Now we are ready to create our first zf2 module we will tackle this in the next part in this tutorial.


12/07/2014 23:06:00 Shaun Freeman Filed Under: ZF2 Tutorial PHP, Zend Framework, zf2

Twitter Feed
Shaun Freeman @Zendmaster

Shaun Freeman @Zendmaster

I liked a @YouTube video https://t.co/lSFWmpHTX1 Patrick Stewart talks about meeting Sting on the set of DUNE (Funny to the EXTREME)

Shaun Freeman @Zendmaster

I added a video to a @YouTube playlist https://t.co/pmXSmod4ti Anonymous - This will Change Everything You Know... (2018-2019)

Shaun Freeman @Zendmaster

I added a video to a @YouTube playlist https://t.co/GkwTCvBfes Will Artificial Intelligence Take Over The World?

Shaun Freeman @Zendmaster

I liked a @YouTube video https://t.co/Y1ulafmsC6 Frank Abagnale: "Catch Me If You Can" | Talks at Google

Shaun Freeman @Zendmaster

I liked a @YouTube video https://t.co/NBdW2xFnqD ETS2: Special Transport DLC Trailer