PHP code example of pixelkarma / pkrouter

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

    

pixelkarma / pkrouter example snippets


use Pixelkarma\PkRouter\PkRouter;

$pkRouter = new PkRouter();

use Pixelkarma\PkRouter\PkRoute;

$pkRouter->routes->addRoute(
  new PkRoute(
    "home", ["GET"], "/",
    function (PkRouter $router) {
      $message = "Hello World!";
      return $router->respond(["message" => $message]);
    }
  )
);
$pkRouter->run();

# ./public/index.php
$pkRouter->routes->addRoute(
  new PkRoute("home", ["GET"], "/", "YourNamespace\Controllers\HelloController@sayHello")
);
$pkRouter->run();

  $pkRouter = new PkRouter(
    $routes = null, // An instance of PkRoutesConfig
    $request = null, // An instance of PkRequest
    $response = null, // An instance of PkResponse
    $logFunction = null // a callable function that excepts one Exception parameter
  );

use Pixelkarma\PkRouter\PkRoute;

$homeRoute = new PkRoute(
  name: "home",
  path: "/",
  methods: ["GET"],
  callback: /* function or class method string */,
  meta: [],
  before: [
    /* PkMiddlewareInterface */
  ],
  after: [
    /* PkMiddlewareInterface */
  ],
);

$pkRouter->routes->addRoute($homeRoute);

$boolResult = $pkRouter->run();

if (true === $pkRouter->match()) {
  $boolResult = $pkRouter->run();
}else{
  // Handle the 404
}

$router->respond(["key"=>"value"], 200);

// Setting up a user object
$router->user = (object)[
  "username" => "j.doe"
];

new PkRoute(
  name: "name",
  path: "/path/",
  methods: ["GET", "POST"],
  callback: "YourNamespace\Controllers\HelloController@sayHello",
  meta: [
    "permissions" => "admin"
    "anything" => "else"
  ],
  before: [
    // PkMiddlewareInterface, - run before route
    // PkMiddlewareInterface, ...
  ],
  after: [
    // PkMiddlewareInterface, - run after route
    // PkMiddlewareInterface, ...
  ]
);

// Function
callback: functionName(PkRouter $router)

// Anonymous Function
callback: function(PkRouter $router){
  $router->respond(["message" => "Hello!"]);
}

// Controller Method
callback: "YourNamespace\Controllers\ExampleController@methodName"

namespace YourNamespace\Controllers;
class ExampleController {
  private $router;
  public function __construct(PkRouter $router) {
    $this->router = $router;
  }
  public function methodName(){
    return $this->router->respond(["message" => "Hello!"]);
  }
}

meta: [
  "userAccess" => ["group1", "group2"],
  "something" => "else"
]

$router->request->getParam('username')

use Pixelkarma\PkRouter\PkRoute;
use Pixelkarma\PkRouter\PkRoutesConfig;

class MyRoutes extends PkRoutesConfig {
  public function routes(): array {
    /**
     *  Match 'Serial Number' 'AA-1234'
     *  /path/AA-1234/ == /path/[sn:serialNumber]/
     */
    PkRoute::addMatchPattern("sn", "(/^[A-Z]{2}-\d{4}$/)");
    /* add routes here */
  }
}

$router->route->getParam("userId", false);
$router->route->getParam("userId", 0);

// Returns key value or all `meta` with `getMeta('name')`
$router->route->getMeta(string $key = null, $default = null)

// Returns key value or all `params` with `getParam('name')`
$router->route->getParam(string $key = null, $default = null)

// Returns route name string
$router->route->getName()

// Returns the path `/user/[s:username]/`
$router->route->getPath()

// Returns an array of allowed methods `["GET", "POST"]`
$router->route->getMethods()

# ./public/index.php
use Pixelkarma\PkRouter\PkRouter;
$pkRouter = new PkRouter(new MyRoutes());
$pkRouter->run();

# ./src/Routes/MyRoutes.php
namespace YourNamespace\Router;

use YourNamespace\Router\Middleware\AuthorizationMiddleware;
use YourNamespace\Router\Middleware\AnalyticsMiddleware;

use Pixelkarma\PkRouter\PkRoute;
use Pixelkarma\PkRouter\PkRoutesConfig;

class MyRoutes extends PkRoutesConfig {
  public function routes(): array {

    // Define Middleware
    $authorizationMiddleware = new AuthorizationMiddleware();
    $analyticsMiddleware = new AnalyticsMiddleware();

    // Create Routes
    $readRoute = new PkRoute(
      name: "read",
      path: "/storage/",
      methods: ["GET"],
      callback: "YourNamespace\Controllers\StorageController@read",
      after: [
        $analyticsMiddleware,
      ]
    );

    $writeRoute = new PkRoute(
      name: "write",
      path: "/storage/",
      methods: ["POST"],
      callback: "YourNamespace\Controllers\StorageController@write",
      before: [
        $authorizationMiddleware,
      ],
      after: [
        $analyticsMiddleware,
      ]
    );

    // Return all routes
    return [$readRoute, $writeRoute];
  }
}

$router->request->getHeader("authorization", false);
$router->request->getHeader("user-agent", "Unknown");

// Returns key value or all `headers` with `getHeader('name')`
$router->request->getHeader(string $key = null, $default = null);

// Returns key value or all `?query=string` with `getQuery('name')`
$router->request->getQuery(string $key = null, $default = null);

// Returns key value or all `body content` with `getBody('name')`
$router->request->getBody(string $key = null, $default = null);

// Returns key value or all `cookies` with `getCookie('name')`
$router->request->getCookie(string $key = null, $default = null);

// Returns key value or all `$_FILES` with `getFile('name')`
$router->request->getFile(string $key = null, $default = null);

// Returns a string like "GET" or "POST"
$router->request->getMethod();

// Returns true if the connection is SSL
$router->request->isSecure();

// Returns the hostname
$router->request->getHost();

// Returns the requested path
$router->request->getPath();

// Returns the Content-Type, usually `application/json`
$router->request->getContentType();

// Returns the RAW body of the request.
$router->request->getRawBody();

// Returns "https" or "http"
$router->request->getScheme();

// Returns the port: 80, 443
$router->request->getPort();

// Returns the `username` in http://username:password@hostname/path
// !DANGER! This is insecure and depreciated. Use with caution.
$router->request->getUser();

// Returns the `password` in http://username:password@hostname/path
// !DANGER! This is insecure and depreciated. Use with caution.
$router->request->getPass();

// Add a response header.
$router->response->setHeader(string $name, string $value = '');

// Clear all set response headers
$router->response->clearHeaders();

// Set the response code (200, 404, 500, ...)
$router->response->setCode(int $code);

// Sends an Array as JSON.
// Optionally set the http response code.
$router->response->sendJson(array $payload, int $code = null);
/* also */ $router->respond(array $payload, int $code = null);

// Sends whatever you pass without processing it.
// Optionally set the http response code.
$router->response->sendRaw($payload, int $code = null);

// Returns the response payload exactly how it was sent.
$router->response->getPayload();

# ./src/Router/CustomResponse.php
namespace YourNamespace\Router;

use Pixelkarma\PkRouter\PkResponse;

class CustomResponse extends PkResponse {
  public function sendXml($xml, int $code = null): bool {
    $this->setHeader('Content-Type', 'application/xml');
    return $this->sendRaw($xml, $code);
  }
}

# ./public/index.php
use YourNamespace\Router\CustomResponse;

// Create PkRouter with your response class
$pkRouter = new PkRouter(
  response: new CustomResponse()
);

# ./src/Controllers/MyController.php
namespace YourNamespace\Controllers;

use Pixelkarma\PkRouter\PkRouter;

class MyController {
  private $router;

  public function __construct(PkRouter $router) {
    $this->router = $router;
  }

  public function getXml(){
    // Execute in your controller/function
    $this->router->response->sendXml($xmlData, int $code = null);
  }
}

new PkRoute(
  /* ... */
  before: [
    /* PkMiddlewareInterface,
       PkMiddlewareInterface */
  ],
  after: [
    /* PkMiddlewareInterface */
  ],
);

namespace YourNamespace\Router\Middleware;

use Pixelkarma\PkRouter\PkMiddlewareInterface;
use Pixelkarma\PkRouter\PkRouter;

class AuthorizationMiddleware implements PkMiddlewareInterface {
  public function handle(PkRouter $router, $previous = null) {
    // Check the headers for `auth-token`
    if (false === $router->request->getHeader("auth-token", false)) {
      $router->response->sendRaw("Unauthorized", 401);
      exit; // Also acceptable to return false or throw and Exception
    }
    $router->user = YourAuthorizationCode(
                      $router->request->getHeader("auth-token")
                    );
    return true;
  }
}

public function handle(PkRouter $router, $previous = 0) {
  $count = $previous + 1;
  print "Count: {$count}\n";
  return $count;
}