zend-framework2 Getting started with zend-framework2 A simple Hello World


Example

In your command line, get in the directory you want to create the project in, then type: composer create-project zendframework/skeleton-application helloWorldTest. During installation, you will be asked if you want a minimal install: Let's say yes for the moment, we are just testing.

For simplicity sake, we will use the built-in PHP CLI server. From the command line, get yourself in the root directory of your project (helloWorldTest), then run : php -S 0.0.0.0:8080 -t public/ public/index.php. Now, open your web browser and go to http://localhost/, you should see the welcome page of the ZF2 Skeleton Application.

If you do so, we will now setup a new page. In module/Application/config/module.config.php you can see that a dynamic route is already setup for the application subfolder:

return [
    'router' => [
        'routes' => [
            'home' => [
                ...
            ],
            'application' => [
                'type'    => Segment::class,
                'options' => [
                    'route'    => '/application[/:action]',
                    'defaults' => [
                        'controller'    => Controller\IndexController::class,
                        'action'        => 'index',
                    ],
                ],
            ],
        ],
    ],

Set a new action "helloWorldAction()" in module/Applicaiton/src/Controller/IndexController.php:

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        ...
    }
    
    public function helloWorldAction()
    {
        return new ViewModel();
    }
}

Finally, create the view file module/Application/view/application/index/hello-world.phtml with the following content:

<?php
echo "Hello World !";

Now, go to http://localhost/application/hello-world, and say hi to ZF2 !