PHP code example of initphp / router

1. Go to this page and download the library: Download initphp/router 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/ */

    

initphp / router example snippets


$config = [
    'paths'                 => [
        'controller'            => null, //The full path to the directory where the Controller classes are kept.
        'middleware'            => null, //The full path to the directory where the Middleware classes are kept.
    ],
    'namespaces'            => [
        'controller'            => null, //Namespace prefix of Controller classes, if applicable.
        'middleware'            => null, //Namespace prefix of Middleware classes, if applicable.
    ],
    'base_path'             => '/', // If you are working in a subdirectory; identifies your working directory.
    'variable_method'       => false, // It makes the request method mutable with Laravel-like $_REQUEST['_method'].
    'argument_new_instance' => false, // This configuration is used for Request and Response objects that you want as arguments.
];


use \InitPHP\HTTP\Message\{Request, Response, Stream};
use \InitPHP\HTTP\Emitter\Emitter;
use \InitPHP\Router\Router;

$request = Request::createFromGlobals();
$response = new Response();

// Create the router object.
$router = new Router($request, $response, []);

// ... Create routes.
$router->get('/', function () {
    return 'Hello World!';
});

$router->post('/login', function (Request $request, Response $response) {
    return $response->json([
        'status'        => 0,
        'message'       => 'Unauthorized',
    ], 401);
});

// If you do not make a definition for 404 errors; An exception is thrown if there is no match with the request.
$router->error_404(function () {
    echo 'Page Not Found';
});

// Resolve the current route and get the generated HTTP response object.
$response = $router->dispatch();

// Publish the HTTP response object.
$emitter = new Emitter;
$emitter->emit($response);

server {
	listen 80;
	server_name myinitphpdomain.dev;
	root /var/www/myInitPHPDomain/public;
	index index.php;
	location / {
		try_files $uri $uri/ /index.php?$query_string;
	}
	location ~ \.php$ {
		fastcgi_split_path_info ^(.+\.php)(/.+)$;
		fastcgi_pass unix:/var/run/php7.4-fpm.sock;
		fastcgi_index index.php;