ennerd/raw

A simple, old school framework for efficiently developing applications.

dev-master 2023-05-22 08:40 UTC

This package is auto-updated.

Last update: 2024-10-22 11:37:54 UTC


README

A very small framework for efficiently writing PHP web applications. The framework focuses on productivity, and prioritizes that over the overengineering that most modern frameworks tend to prioritize.

Function Reference

/**
 * Shared Cache, where cached values are available across requests and multiple
 * servers.
 */
Raw::cache();                           // Returns an instance of Raw\Cache
Raw::cache()->set($key, $value, $ttl);  // Cache some value in a shared cache
Raw::cache()->get($key, &$found=null);  // Get a cached value from the shared cache
Raw::cache()->has($key);                // Check if a shared cached value exists
Raw::cache()->unset($key);              // Remove a value from the shared cache
/**
 * Shared Configuration, where configuration values are shared across all requests
 * on the same server.
 */
Raw::config();                          // Returns an instance of Raw\Config
Raw::config()->rootPath;                // The path to the folder where composer.json is stored
Raw::config()->databaseUser;            // The value of MYSQL_USER environment variable
Raw::config()->databasePassword;        // The value of MYSQL_PASSWORD environment variable
Raw::config()->databaseHost;            // The value of MYSQL_HOST environment variable
Raw::config()->databaseName;            // The value of MYSQL_DATABASE environment variable
Raw::config()->databaseDSN;             // The database DSN (a PDO DSN string constructed from environment variables)
/**
 * Context, where all information pertaining to the specific request being processed
 * is stored. If your application is a ReactPHP or Swoole application, it is essential
 * that you access the context via this method, instead of storing data in a global
 * variable.
 */
Raw::context();                                 // Returns an instance of Raw\Context
Raw::context()->db();                           // Connects to the database and returns an instance of Raw\DB
Raw::context()->db()->query($sql, ...$vars);    // Performs an SQL query and returns a Traversable<stdClass>
Raw::context()->db()->queryField($sql, ...$vars); // Performs an SQL query and returns a single value
Raw::context()->db()->queryRow($sql, ...$vars); // Performs an SQL query and returns an stdClass instance
Raw::context()->db()->exec($sql, ...$vars);     // Performs an update query and returns the number of affected rows
Raw::context()->db()->lastInsertId();           // Returns the last inserted auto increment id
Raw::context()->pdo();                          // Connects to the database and returns an instance of \PDO
Raw::context()->cache();                        // Returns an instance of Raw\Cache
Raw::context()->cache()->set($key, $value, $ttl);  // Cache some value in a short lived per-request cache
Raw::context()->cache()->get($key, &$found=null);  // Get a cached value from the short lived per-request cache
Raw::context()->cache()->has($key);                // Check if a key exists in the short lived per-request cache
Raw::context()->cache()->unset($key);              // Remove a value from the short lived per-request cache
Raw::context()->request();                      // Return the instance of Raw\Request which is currently being processed
Raw::context()->request()->get($key);           // Return the value of the query parameter $key
Raw::context()->request()->post($key);          // Return the value of the http post data form field $key
Raw::context()->request()->header($key);        // Return the value of the http request header $key
Raw::context()->request()->method();            // Return the request verb ("GET", "POST", "PUT" etc)
Raw::context()->response();                     // Return the instance of Raw\Response which handles sending a response
Raw::context()->response()->header($key, $value, $replace=false); // Set an HTTP response header
Raw::context()->response()->status($code, $reason=null); // Set the response status code (200, 404 etc)
Raw::context()->response()->cacheTTL($ttl)      // Reduce the cacheability of this response to $ttl seconds
Raw::context()->response()->cachePublic($ttl=null); // set Cache-Control: public, max-age=$ttl unless previously private/no-cache
Raw::context()->response()->cachePrivate($ttl=null); // Set Cache-Control: private, max-age=$ttl unless previously no-cache
Raw::context()->response()->cacheOff($noStore=false); // Set Cache-Control: no-cache or no-store
Raw::context()->response()->write($chunk);      // Write a string to the response body
Raw::context()->response()->end($chunk=null);   // Close the response (optionally writing a string to the response body)
/**
 * Logger is used for logging events and activities.
 */
Raw::logger()->emergency($message, $context=[]);
Raw::logger()->alert($message, $context=[]);
Raw::logger()->critical($message, $context=[]);
Raw::logger()->error($message, $context=[]);
Raw::logger()->warning($message, $context=[]);
Raw::logger()->notice($message, $context=[]);
Raw::logger()->info($message, $context=[]);
Raw::logger()->debug($message, $context=[]);
Raw::logger()->log($level, $message, $context=[]);
/**
 * Session is an object which is saved across multiple requests per browser.
 */
Raw::session();                                 // Creates a new session if one does not already exist and return a Raw\Cache instance
Raw::session()->set($key, $value, $ttl);        // Store a value in the session
Raw::session()->get($key, &$found=null);        // Get a value from the session
Raw::session()->has($key);                      // Check if a key exists in the session
Raw::session()->unset($key);                    // Remove a value from the session

Routing and request handling

Raw framework has a strong focus on performance and scalability. For this reason, the framework will not load or instantiate controllers unless they are needed.

A controller will be instantiated if a request is received for the "base route" for it. The base route is the shortest path that the controller will handle requests for.

Example base routes:

  • /users will instantiate the controller with no arguments for the constructor.
  • /users/<id> will instantiate the controller with id from the path passed to the constructor.

Multiple controllers can subscribe to the same routes; each controller has an internal router which will determine which method will be called for that controller.

Example controller


use Raw\Route;

class Users extends Raw\Controller {

    #[Route("/")]
    public function index() {
        return "Lists all users";
    }

    #[Route("/:id")]
    public function retrieve(int $id) {
        return "User id $id";
    }

    /**
     * A handler can be annotated with multiple routes
     */
    #[Route("/:id", ["POST"])]
    #[Route("/:id/edit", ["GET", "POST"])]
    public function edit(int $id) {
        return "Edit user id $id";
    }

    #[Route("/:id", ["DELETE"])]
    #[Route("/:id/delete", ["GET", "POST"])]
    public function delete(int $id) {
        return "Delete user id $id";
    }

}

When the class has been declared, you can mount the controller

Raw::router()->mount('/users', Users::class);

The controller will be loaded whenever the request URL matches /users. A request for /users/123 will invoke the User::retrieve() method.

Configuration Reference

Raw framework is configured via environment variables. The following is a complete reference of the environment variables the framework respects. All configuration options are accessible via Raw::config()->* variables.

  • MYSQL_HOST: The hostname or IP address of your MySQL server.
  • MYSQL_PORT: The port number your MySQL server is listening on. Defaults to 3306.
  • MYSQL_DATABASE: The name of the MySQL database you want your application to connect to.
  • MYSQL_USER: The username for your MySQL database.
  • MYSQL_PASSWORD: The password for your MySQL database.
  • MYSQL_CHARSET: The charset to use for your MySQL database connection. If not specified, the default charset used is "utf8mb4".
  • HTTP_PROXY: Specifies the HTTP Proxy to be used for HTTP requests made by your application. If not specified, no proxy will be used.
  • HTTP_CLIENT_TIMEOUT: The timeout (in seconds) for HTTP client requests. If not specified, the default timeout is set to 10 seconds.
  • HTTP_CLIENT_USER_AGENT: The User-Agent string to use for HTTP client requests. If not specified, the default User-Agent string is 'Raw/1.0'.