CodeIgniter4 Attribute Routes. You can set Routes in Controllers as PHP8 Attributes.

Overview

CodeIgniter4 Attribute Routes

This package generates a Routes File from the Attribute Routes in your Controllers.

  • You can set routes in your Controllers, and disable Auto Routing.
  • It generates a Routes File, so, there is no extra overhead at runtime.
  • The generated Routes File can be used on PHP 7.3 production servers.
use Kenjis\CI4\AttributeRoutes\Route;

class SomeController extends BaseController
{
    #[Route('path', methods: ['get'])]
    public function index()
    {
        ...
    }
}

Requirements

  • CodeIgniter 4.1.7 or later
  • Composer
  • PHP 8.0 or later

Installation

$ composer require kenjis/ci4-attribute-routes:~0.1.0

Configuration

  1. Add the following code to the bottom of your app/Config/Routes.php file:
/*
 * Attribute Routes
 *
 * To update the route file, run the following command:
 * $ php spark route:update
 *
 * @see https://github.com/kenjis/ci4-attribute-routes
 */
if (file_exists(APPPATH . 'Config/RoutesFromAttribute.php')) {
    require APPPATH . 'Config/RoutesFromAttribute.php';
}
  1. Disable auto routing and enable route priority:
--- a/app/Config/Routes.php
+++ b/app/Config/Routes.php
@@ -22,7 +22,8 @@ $routes->setDefaultController('Home');
 $routes->setDefaultMethod('index');
 $routes->setTranslateURIDashes(false);
 $routes->set404Override();
-$routes->setAutoRoute(true);
+$routes->setAutoRoute(false);
+$routes->setPrioritize();

This is optional, but strongly recommended.

Quick Start

1. Add Attribute Routes to your Controllers

Add #[Route()] attributes to your Controller methods.

<?php
namespace App\Controllers;

use Kenjis\CI4\AttributeRoutes\Route;

class News extends BaseController
{
    #[Route('news', methods: ['get'])]
    public function index()
    {
        ...
    }
}

2. Update Routes File

$ php spark route:update

APPPATH/Config/RoutesFromAttribute.php is generated.

Check your routes with the php spark routes command.

Route Attributes

Route

#[Route('news', methods: ['get'])]
#[Route('news/create', methods: ['get', 'post'])]
#[Route('news/(:segment)', methods: ['get'], options: ['priority' => 1])]

RouteGroup

use Kenjis\CI4\AttributeRoutes\RouteGroup;

#[RouteGroup('', options: ['filter' => 'auth'])]
class GroupController extends BaseController
{
    #[Route('group/a', methods: ['get'])]
    public function getA(): void
    {
        ...
    }
    ...
}

RouteResource

use Kenjis\CI4\AttributeRoutes\RouteResource;

#[RouteResource('photos', options: ['websafe' => 1])]
class ResourceController extends ResourceController
{
    ...
}

RoutePresenter

use Kenjis\CI4\AttributeRoutes\RoutePresenter;

#[RoutePresenter('presenter')]
class PresenterController extends ResourcePresenter
{
    ...
}

Trouble Shooting

No routes in the generated routes file

You must import the attribute classes in your controllers.

E.g.:

use Kenjis\CI4\AttributeRoutes\Route;
...
    #[Route('news', methods: ['get'])]
    public function index()

Can't be routed correctly, or 404 error occurs

Show your routes with the php spark routes command, and check the order of the routes. The first matched route is the one that is executed. The placeholders like (.*) or ([^/]+) takes any characters or segment. So you have to move the routes like that to the bottom.

In one controller, you can move the methods having such routes to the bottom.

Or set the priority of the routes with options:

#[Route('news/(:segment)', methods: ['get'], options: ['priority' => 1])]

Zero is the default priority, and the higher the number specified in the priority option, the lower route priority in the processing queue.

For Development

Installation

composer install

Available Commands

composer test              // Run unit test
composer tests             // Test and quality checks
composer cs-fix            // Fix the coding style
composer sa                // Run static analysys tools
composer run-script --list // List all commands
You might also like...
MenuCard - Employees can login with already made admin accounts

MenuCard Symfony 5.4.2 application Employees can login with already made admin accounts. Employees can manages create new accounts for new employees.

A Laravel package that can be used for fetching favicons from websites
A Laravel package that can be used for fetching favicons from websites

A Laravel package that can be used for fetching favicons from websites.

Rafa Cake and Bakery is a web-based application project that aims to introduce Rafa Cake and Bakery, introduce what products are sold and can also order them via Whatsapp.

Rafa-cake-and-bakery Rafa Cake and Bakery is a web-based application project that aims to introduce Rafa Cake and Bakery, introduce what products are

A wiki to ease developers' work by providing a user authentication librariesthat can be used as middleware within a web application to authenticate

A wiki to ease developers' work by providing a user authentication librariesthat can be used as middleware within a web application to authenticate (their application user) requests.

Crater is an open-source web & mobile app that helps you track expenses, payments & create professional invoices & estimates.
Crater is an open-source web & mobile app that helps you track expenses, payments & create professional invoices & estimates.

Introduction Crater is an open-source web & mobile app that helps you track expenses, payments & create professional invoices & estimates. Web Applica

Cloudlog is a self-hosted PHP application that allows you to log your amateur radio contacts anywhere.

Web based amateur radio logging application built using PHP & MySQL supports general station logging tasks from HF to Microwave with supporting applications to support CAT control.

This is a plugin written in PHP programming language and running on the PocketMine platform that works stably on the API 4.0.0 platform. It allows you to query some other server information
This is a plugin written in PHP programming language and running on the PocketMine platform that works stably on the API 4.0.0 platform. It allows you to query some other server information

QueryServer This is a plugin written in PHP programming language and running on the PocketMine platform that works stably on the API 4.0.0 platform. I

A simple tool that I share with you. This tool serves to make conversions from text to audio Google Translate.

A simple tool that I share with you. This tool serves to make conversions from text to audio Google Translate. You can download this conversion 100% for free. Good luck.

DaybydayCRM an open-source CRM, to help you keep track of your daily workflow.
DaybydayCRM an open-source CRM, to help you keep track of your daily workflow.

====================== DaybydayCRM is an everyday customer relationship management system (CRM) to help you keep track of your customers, tasks, appoi

Comments
  • Abstract Controllers

    Abstract Controllers

    I have created an abstract CRUD controller which has all the routes defined for typical CRUD use case.

    However the attributes are read and declaring class that is used is an abstract one. Defined routes are now pointing to a class that can not be constructor. Could you add the possibility for it use the child class instead?

    opened by KrisDriv 4
Releases(v0.3.0)
  • v0.3.0(Nov 8, 2022)

    What's Changed

    • chore: add composer unused by @kenjis in https://github.com/kenjis/ci4-attribute-routes/pull/4
    • Update for PHP 8.2 by @kenjis in https://github.com/kenjis/ci4-attribute-routes/pull/5

    Full Changelog: https://github.com/kenjis/ci4-attribute-routes/compare/v0.2.0...v0.3.0

    Source code(tar.gz)
    Source code(zip)
  • v0.2.0(Feb 13, 2022)

    What's Changed

    • feat: improve output code by @kenjis in https://github.com/kenjis/ci4-attribute-routes/pull/2
    • feat: add method validation by @kenjis in https://github.com/kenjis/ci4-attribute-routes/pull/3

    Full Changelog: https://github.com/kenjis/ci4-attribute-routes/compare/v0.1.0...v0.2.0

    Source code(tar.gz)
    Source code(zip)
  • v0.1.0(Jan 27, 2022)

Owner
kenjis
kenjis
A great looking and easy-to-use photo-management-system you can run on your server, to manage and share photos.

Lychee A great looking and easy-to-use photo-management-system. Since the 1st of April 2018 this project has moved to it's own Organisation (https://g

Tobias Reich 6.2k Jan 5, 2023
This is a Task Manager system for managing your task. You can categorize your tasks and upload music to the project And a whole host of other features

taskManager Login and register Each user can have their own task Categorize tasks by creating folders Edit and Delete Folders Search for Tasks Show nu

masoudharooni 11 May 22, 2022
A blog website where you can create/edit/delete blogs.

A blog website where you can create/edit/delete blogs. All the data will be caught from the DB, but here's the catch: I'm doing this project in Laravel 8.

null 1 Dec 8, 2021
This is a simple blog system, you can sign up and create post.

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Nnadi Chimezie Charles 1 Jan 8, 2022
This mini project aims to design a set of APIs that manage transactions of a company

Introduction. This mini project aims to design a set of APIs that manage transactions of a company.Managing transactions include: creating transaction

Omar Hossam Eldin Kandil 2 May 22, 2022
Uploader is a set of small classes for sending images, files, and media received by a form of your application

Uploader is a set of small classes for sending images, files, and media received by a form of your application. The Uploader handles, validates and sends the files to your server. Image class can still handle sizes with the gd library.

null 5 Dec 22, 2022
Server manager is a open source project made for people so that they can add the servers to one single place irrespective of their provider and manage it through one location.

Server Manager Are you sick of having to log into hundreads of different website just to access your server? Well we got you, Server manager is a open

null 8 Aug 9, 2022
Build a health check report that can be verified with Oh Dear

Create a health check report to be verified by Oh Dear Using this package you can build up the JSON that Oh Dear expects for the health check. Install

Oh Dear 5 Oct 6, 2022
User input collection of recipes that can be filtered to meet certain criteria or to return a random recipe.

How to use: Install xampp: https://www.apachefriends.org/index.html and PHP Unzip the repo in the C:/xampp/htdocs directory Run xampp and turn on the

kristiyan 1 Jan 27, 2022