Controllers

Controllers are classes that define action methods that respond to a request. Define your controllers within app/controllers folder.

<?php

namespace App\Controllers;

class HomeController
{
    public function index()
    {
        return 'welcome';
    }
}

As you can see, defining controllers in Lightpack is quite easy.

Route Params

For dynamic routes, you can access route parameters by defining them in the controller's action method signature. For example, for the following route definition:

route()->get('/users/:user/posts/:post', PostController::class);

Define your controller as:

<?php

namespace App\Controllers;

class PostController
{
    public function index($user, $post)
    {
        // ...
    }
}

Rendering Views

Define your view templates in app/views folder. To render a view template, call the view() method of response(). This method takes a view template name and an optional array of view data as arguments.

<?php

namespace App\Controllers;

class PageController
{
    return response()->view('page');
}

You can pass view data as second argument to render() method.

class PageController
{
    public function index()
    {
        return response()->view('page', [
            'title' => 'Lightpack PHP',
        ]);
    }
}

Now you can access the view data array by key names as variables within your view template files. For example, if you want to access the title variable, you can do it as follows:

Title: <?= $title ?>

Read more about view templating support in Lightpack.

JSON Response

For APIs, you may be interested in sending JSON response instead of view templates. For that, simply call the json() method inherited from parent class.

return response()->json(['framework' => 'Lighpack']);

XML Response

For sending XML response, simply call the xml() method inherited from parent class passing it the XML formatted string data.

return response()->xml('xml_data_string');

Calling methods view(), or json(), or xml() automatically takes care of setting appropriate response content type and status code 200, thereby saving you some typing. However, you can set them manually using the methods available in response() object.

Read more about using response() in Lightpack PHP.