Including Routes in Packages

Including routes in packages is very similar to including them in application/bootstrap/app.php. In our example, let’s say our package handle is “classifieds”.

Set Up Autoloading

First, set up autoloading in your package to point a namespace “Aembler\Classifieds” at packages/classifieds/src. You do this by adding a $pkgAutoloaderRegistries entry into the packages/classifieds/controller.php file.

protected $pkgAutoloaderRegistries = [
    'src/' => ‘Aembler\\Classifieds’
];

Now, when the package is installed, this autoloader prefix will be enabled.

Create Your RouteList file.

Next, create your route list file. As mentioned before, it can contain individual routes or route groups. Place it at packages/classifieds/src/RouteList.php. It will then need the class name Aembler\Classifieds\RouteList. packages/classifieds/src/RouteList.php will look like this:

<?php
namespace Aembler\Classifieds;
use Concrete\Core\Routing\RouteListInterface;
use Concrete\Core\Routing\Router;
class RouteList implements RouteListInterface
{
    public function loadRoutes($router)
    {
        // Routes and route groups go here.
    }
}

Specify the Package Handle in Any Route Groups

If you’re loading your routes from a file in a route group as described in Grouping Routes, you’ll need to pass a package handle as the second parameter to the routes() method of your group.

$router->buildGroup()
->routes(‘routes.php’, ‘classifieds’);

This will load routes from the file packages/classifieds/routes/routes.php.

Register in on_start()

Since the on_start() method of a package controller runs early on concrete5 request, it’s a perfect place to register our route list. Add

use Aembler\Classifieds\RouteList;

to the top of the packages/classifieds/controller.php file, and then

public function on_start()
{
    $router = $this->app->make(‘router’);
    $list = new RouteList();
    $list->loadRoutes($router);
}

That’s it! The routes defined in your package’s route list are now registered and will accept requests.