PHP code example of pmjones / auto-route

1. Go to this page and download the library: Download pmjones/auto-route library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

pmjones / auto-route example snippets


namespace Project\Http\Photo;

class GetPhoto
{
    public function __invoke(int $photoId)
    {
        // ...
    }
}

namespace Project\Http\Photo\Edit;

class GetPhotoEdit // parent: GetPhoto
{
    public function __invoke(int $photoId)
    {
        // ...
    }
}

namespace Project\Http\Photos\Archive;

class GetPhotosArchive
{
    public function __invoke(int $year = null, int $month = null)
    {
        // ...
    }
}

namespace Project\Http\Photos\ByTag;

class GetPhotosByTag
{
    public function __invoke(string $tag, string ...$tags)
    {
        // ...
    }
}

use AutoRoute\AutoRoute;

$autoRoute = new AutoRoute(
    'Project\Http',
    dirname(__DIR__) . '/src/Project/Http/'
);

use AutoRoute\AutoRoute;

$autoRoute = new AutoRoute(
    namespace: 'Project\Http',
    directory: dirname(__DIR__) . '/src/Project/Http/',
);

$router = $autoRoute->getRouter();
$route = $router->route($request->method->name, $request->url->path);

use AutoRoute\Exception;

switch ($route->error) {
    case null:
        // no errors! create the action class instance
        // ... and call it with the method and arguments.
        $action = Factory::newInstance($route->class);
        $method = $route->method;
        $arguments = $route->arguments;
        $response = $action->$method(...$arguments);
        break;

    case Exception\InvalidArgument::CLASS:
        $response = /* 400 Bad Request */;
        break;

    case Exception\NotFound::CLASS:
        $response = /* 404 Not Found */;
        break;

    case Exception\MethodNotAllowed::CLASS:
        $response = /* 405 Not Allowed */;
        /*
        N.b.: Examine $route->headers to find the 'allowed' methods for the
        resource, if any.
        */
        break;

    default:
        $response = /* 500 Server Error */;
        break;
}

$route = $router->route($request->method->name, $request->url->path);
print_r($route->messages);

$generator = $autoRoute->getGenerator();

use Project\Http\Photo\Edit\GetPhotoEdit;
use Project\Http\Photos\ByTag\GetPhotosByTag;

$path = $generator->generate(GetPhotoEdit::CLASS, 1);
// /photo/1/edit

$path = $generator->generate(GetPhotosByTag::CLASS, 'foo', 'bar', 'baz');
// /photos/by-tag/foo/bar/baz

$autoRoute = new AutoRoute(
    // ...
    baseUrl: '/api',
);

namespace Project\Http\Photo;

use SapiRequest;

class PatchPhoto
{
    public function __invoke(SapiRequest $request, int $id)
    {
        // ...
    }
}

$autoRoute = new AutoRoute(
    // ...
    ignoreParams: 1,
);

// determine the route
$route = $router->route($request->method, $request->url[PHP_URL_PATH]);

// create the action object
$action = Factory::newInstance($route->class);

// pass the request first, then any route params
$response = call_user_func([$action, $route->method], $request, ...$route->arguments);

$autoRoute = new AutoRoute(
    // ...
    loggerFactory: function () {
        // return a \Psr\Log\LoggerInterface implementation
    },
);

$autoRoute = new AutoRoute(
    // ...
    method: 'exec',
);

$autoRoute = new AutoRoute(
    // ...
    suffix: 'Action',
);


$autoRoute = new AutoRoute(
    // ...
    wordSeparator: '_',
);

namespace Project\Http\Photo;

class GetPhoto
{
    public function __invoke($photoId)
    {
    }
}

/* GET /company/{companyId} # get an existing company */
namespace Project\Http\Company;

class GetCompany // no parent resource
{
    public function __invoke(int $companyId)
    {
        // ...
    }
}

/* POST /company # add a new company*/
class PostCompany // no parent resource
{
    public function __invoke()
    {
        // ...
    }
}

/* PATCH /company/{companyId} # edit an existing company */
class PatchCompany // no parent resource
{
    public function __invoke(int $companyId)
    {
        // ...
    }
}

/* GET /company/{companyId}/employee/{employeeNum} # get an existing company employee */
namespace Project\Http\Company\Employee;

class GetCompanyEmployee // parent resource: GetCompany
{
    public function __invoke(int $companyId, int $employeeNum)
    {
        // ...
    }
}

/* POST /company/{companyId}/employee # add a new company employee */
namespace Project\Http\Company\Employee;

class PostCompanyEmployee // parent resource: PostCompany
{
    public function __invoke(int $companyId)
    {
        // ...
    }
}

/* PATCH /company/{companyId}/employee/{employeeNum} # edit an existing company employee */
namespace Project\Http\Company\Employee;

class PatchCompanyEmployee // parent resource: PatchCompany
{
    public function __invoke(int $companyId, int $employeeNum)
    {
        // ...
    }
}

namespace Project\Http\Photos\Archive;

use SapiResponse;

class GetPhotosArchive
{
    public function __invoke(
        int $year = null,
        int $month = null,
        int $day = null
    ) : SapiResponse
    {
        $payload = $this->domain->fetchAllBySpan($year, $month, $day);
        return $this->responder->response($payload);
    }
}

namespace Project\Domain;

class PhotoService
{
    public function fetchAllBySpan(
        ?int $year = null,
        ?int $month = null,
        ?int $day = null
    ) : Payload
    {
        $select = $this->atlas
            ->select(Photos::class)
            ->orderBy('year DESC', 'month DESC', 'day DESC');

        if ($year !== null) {
            $select->where('year = ', $year);
        }

        if ($month !== null) {
            $select->where('month = ', $month);
        }

        if ($day !== null) {
            $select->where('day = ', $day);
        }

        $result = $select->fetchRecordSet();
        if ($result->isEmpty()) {
            return Payload::notFound();
        }

        return Payload::found($result);
    }
}

namespace Project\Http\Company;

use Domain\Company\CompanyId;

class GetCompany
{
    // ...
    public function __invoke(int $companyId)
    {
        // ...
        $payload = $this->domain->fetchCompany(
            new CompanyId($companyId)
        );
        // ...
    }
}

namespace Domain\Company;

use Domain\ValueObject;

class CompanyId extends ValueObject
{
    public function __construct(protected int $companyId)
    {
    }
}

namespace Project\Http\Company;

use Domain\Company\CompanyId;

class GetCompany
{
    // ...
    public function __invoke(CompanyId $companyId)
    {
        // ...
        $payload = $this->domain->fetchCompany($companyId);
        // ...
    }
}

namespace Domain\Photo;

use Domain\Exception\InvalidValue;
use Domain\ValueObject;

class Year extends ValueObject
{
    public function __construct(protected int $year)
    {
        if ($this->year < 0 || $this->year > 9999) {
            throw new InvalidValue("The year must be between 0000 and 9999.");
        }
    }
}

// wrong:
$path = $generator->generate(GetCompany::CLASS, new CompanyId(1));

// right:
$path = $generator->generate(GetCompany::CLASS, 1);


namespace Project\Http\Foos;

use SapiRequest;

class GetFoos
{
    public function __construct(
        SapiRequest $request,
        FooService $fooService
    ) {
        $this->request = $request;
        $this->fooService = $fooService;
    }

    public function __invoke(int $fooId)
    {
        $host = $this->request->headers['host'] ?? null;
        $bar = $this->request->get['bar'] ?? null;
        $body = json_decode($this->request->content, true) ?? [];

        $payload = $this->fooService->fetch($host, $foo, $body);
        // ...
    }
}

namespace Project\Domain;

class FooService
{
    public function fetch(int $fooId, string $host, string $bar, array $body)
    {
        // ...
    }
}

App/
    Http/
        Get.php                     GET /               (root)
        Photos/
            GetPhotos.php           GET /photos         (browse/index)
        Photo/
            DeletePhoto.php         DELETE /photo/1     (delete)
            GetPhoto.php            GET /photo/1        (read)
            PatchPhoto.php          PATCH /photo/1      (update)
            PostPhoto.php           POST /photo         (create)
            Add/
                GetPhotoAdd.php     GET /photo/add      (form for creating)
            Edit/
                GetPhotoEdit.php    GET /photo/1/edit   (form for updating)

$ php bin/autoroute-dump.php Project\\Http ./src/Http

$ php bin/autoroute-create.php Project\\Http ./src/Http GET /photo/{photoId}