Simple and easy to use

A MVC framework in PHP for beginners

The PHP framework
created to make your study of MVC easier.

Documentation

Documentation

Installation

First of all, make sure you have installed PHP and Composer. Clone or download project and install dependencies (composer install).

            
composer install
            
            

Routes

To create a route, in route/router.php, add your route within the rotas function, as shown in the example. Use the $router object, calling the method that corresponds to the HTTP verb you want to use. As parameters, you should pass the route and the controller along with the method you want to call. This framework uses the nikic/fast-route library. Read its documentation for more information.



route -> Required This parameter indicates the route that will be accessed by the user. The route must start with a slash (/).
action -> Required This parameter indicates the controller and method that will be called when the route is accessed. The controller and method must be separated by two colon (:).

<?php

/*
|------------------------------------------------------------------------------------------------------
| Routes
|------------------------------------------------------------------------------------------------------
|
| Here is where you can register routes for your application.
| For more information see https://github.com/nikic/FastRoute
|
*/

function routes(FastRoute\RouteCollector $router): void
{
    $router->get('/', 'App\Controllers\IndexController::index');
    $router->get('/your-url', 'App\Controllers\YourController::yourMethod');
}
            

Controllers

You must extend Core/Controller in your controller class as in the example on the side. The class and method name (action) are the same you registered in router.php, and then, it will be called when the route is accessed. Your controller class will inherit the view() method, which is responsible for rendering a view. You can specify the view in the first parameter and pass data through the second parameter. Here is the description of the view method parameters:

viewName ->Required This parameter indicates the name of the View that should be shown on the screen. The target file extension must be .html, .phtml or .php.
params -> Not required This parameter receives the data that must be passed to be used in the View. The expected data type is a key-value array. Remembering that the name of the key in the array will be the same variable name in the View.

              
<?php

namespace App\Controllers;

use Core\Controller;

class UserController extends Controller {

    public function signIn() {
        $params = [
            'user' => [
                'name' => 'John Doe',
                'email' => 'john.doe@domain.com',
            ]
        ];

        $this->view('home', $params);
    }
}
              
            

Request

The Request class is a utility class that provides methods to access various information related to an HTTP request. It is designed to be injected into a controller action (method) to handle request-related tasks. That means all controllers have access to the Request class by parameters, therefore, just set the parameter in your controller method and use it, like the example below.

Note: Remember to adjust the usage according to your specific application needs. The Request class provides a convenient way to access request-related information within your controllers.

The Request class has the following methods:

getParams(): array -> Returns the entire array of request parameters.
method(): string -> Returns the request method (e.g. GET, POST, PUT, PATCH).
isMethod(string $type): bool -> Checks if the request method is equal to the parameter passed.
ip(): string -> Retrieves the client’s IP address.
path(): string -> Gets the request URI.
ssl(): bool -> Determines if the request is using SSL.
fullPath(): string -> Retrieves the full URL of the request.
var(string $inputName = null): mixed -> Gets parameters from the URI.
query(string $inputName = null): mixed -> Gets parameters from the querystring.
body(string $inputName = null, mixed $default = null): mixed -> Gets parameters from the request body (for POST, PUT, and PATCH requests). $default parameter defines a default value if the parameter is not found.

              
<?php

namespace App\Controllers;

use Core\Controller;
use Core\Request;

class MyController
{
    public function handleRequest(Request $request)
    {
        // Example usage:
        $method = $request->method();
        $uri = $request->path();
        $queryParams = $request->query();
        $postParam = $request->body('postParam1', 'default');
        // ... other logic
    }
}
              
            

Session

The Session class is a tool for managing PHP sessions. It encapsulates the session handling process in an object-oriented manner, providing a clean, intuitive and secure interface for session management. It follows the Singleton design pattern, meaning only one instance of this class can exist at a time. It provides methods to set and get session variables, set the session expiration time, and destroy the session.

You can set a session variable setting this variable in the session instance like an attribute. The same is for recovering a session variable. For example, you can set a user session variable with $session->user = $user. See example below.

The Session class has the following methods:

getInstance(int $expire_time = null): Session -> Returns the session instance. If an instance doesn’t exist, it creates one. The $expire_time parameter is optional and sets the session expiration time in seconds.
setExpiretime(int $__value = null): void -> Sets the session expiration time in seconds.
getExpiretime(): int -> Retrieves the session expiration time in seconds.
set(string $__name, $__value): void -> Sets a session variable.
get(string $__name = null): mixed -> Retrieves a session variable.
delete(string $name): void -> Deletes a session variable.
destroy(): void -> Destroys the session, removing all session variables.

              
<?php

namespace App\Controllers;

use Core\Controller;
use Core\Session;

class AuthenticateController extends Controller
{
    public function login()
    {
        // Get the Session instance
        $session = Session::getInstance();

        // Set a session variable
        $session->set('user', 'John Doe');
        $session->email = 'john.doe@example.com';

        // ... continue with the logic
    }

    public function logout()
    {
        // Get the Session instance
        $session = Session::getInstance();

        // Destroy session
        $session->destroy();

        // continue...
    }
}
              
            

Cookie

The Cookie class provides a secure and easy way to create, read, update and delete cookies. It abstracts the complexity of cookie handling and provides a clean and intuitive interface for managing cookies in PHP. See example below.

The Cookie class offers several methods for manipulating cookies. Let's take a look at each of them:

getName(): string -> Returns the name of the cookie.
getValue(): mixed|null -> Returns the value of the cookie.
setValue(mixed $value): self -> Sets the value of the cookie.
getExpiryTime(): int -> Returns the expiration time of the cookie as a Unix timestamp.
setExpiryTime(int $expiryTime): self -> Sets the expiration time of the cookie as a Unix timestamp.
getPath(): string -> Returns the server path on which the cookie is valid. If the path has not been set, an empty string will be returned.
setPath(string $path): self -> Sets the server path on which the cookie will be valid. This method returns the Cookie class instance itself to allow method chaining.
getDomain(): string|null -> Returns the domain for which the cookie is valid. If the domain has not been set, null will be returned.
setDomain(string $domain): self -> Sets the domain for which the cookie will be valid. This method returns the Cookie class instance itself to allow method chaining.
getMaxAge(): int -> Returns the maximum age of the cookie (i.e. the remaining lifetime).
setMaxAge(int $maxAge): self -> Sets the expiry time for the cookie based on the specified maximum age.
isHttpOnly(): bool -> Returns whether the cookie should be accessible through HTTP only.
setHttpOnly(bool $httpOnly): self -> Sets whether the cookie should be accessible through HTTP only.
isSecureOnly(): bool -> Returns whether the cookie should be sent over HTTPS only.
setSecureOnly(bool $secureOnly): self -> Sets whether the cookie should be sent over HTTPS only.
getSameSiteRestriction(): ?string -> Returns the same-site restriction of the cookie.
setSameSiteRestriction(?string $sameSiteRestriction): self -> Sets the same-site restriction for the cookie.
save(): bool -> Saves the cookie.
saveAndSet(): bool -> Saves the cookie and immediately creates the corresponding variable in the superglobal `$_COOKIE` array.
delete(): bool -> Deletes the cookie.
deleteAndUnset(): bool -> Deletes the cookie and immediately removes the corresponding variable from the superglobal `$_COOKIE` array.
__toString(): string -> Returns the cookie as a string formatted for the HTTP header.
(static) setcookie(string $name, mixed|null $value = null, int $expiryTime = 0, ?string $path = null, ?string $domain = null, bool $secureOnly = false, bool $httpOnly = false, ?string $sameSiteRestriction = null): bool -> Sets a new cookie in a way compatible to PHP's `setcookie(...)` function.
(static) buildCookieHeader(string $name, mixed|null $value = null, int $expiryTime = 0, ?string $path = null, ?string $domain = null, bool $secureOnly = false, bool $httpOnly = false, ?string $sameSiteRestriction = null): ?string -> Builds the HTTP header that can be used to set a cookie with the specified options.
(static) parse(string $cookieHeader): ?Cookie -> Parses the given cookie header and returns an equivalent cookie instance.
(static) exists(string $name): bool -> Checks whether a cookie with the specified name exists.
(static) get(string $name, mixed|null $defaultValue = null): mixed -> Returns the value from the requested cookie or, if not found, the specified default value.
(static) isNameValid(string $name): bool -> Checks whether the cookie name is valid.
(static) isExpiryTimeValid($expiryTime): bool -> Checks whether the expiry time is valid.
(static) calculateMaxAge($expiryTime): int -> Calculates the maximum age based on the expiry time.
(static) formatExpiryTime($expiryTime, $forceShow = false): ?string -> Formats the expiry time.
(static) formatMaxAge($expiryTime, $forceShow = false): ?string -> Formats the max age.
(static) normalizeDomain($domain = null): ?string -> Normalizes the domain.
(static) addHttpHeader($header): bool -> Adds the HTTP header.

Models and Database

You must create a .env file at the root of your project. You can copy the .env.example file and set the environment variables as shown in the example below.

                
DRIVER=mysql
HOST=localhost
DBNAME=
DBUSER=
DBPASSWORD=
                
              

Done! Configs ready! Now we can create our Model and connect to the database.

In your model class, you can use Database class with use Core\Database;. It provides an interface for interacting with the database. This class follows the Singleton design pattern to ensure that only one instance of the database connection is created throughout the application, thereby saving resources.

This class is useful in Models as it provides a structured and reusable way to interact with the database. It abstracts the complexity of database operations, making it easier to perform CRUD (Create, Read, Update, Delete) operations.

Please note that the actual usage of this class may vary depending on the specific requirements of your application. Always ensure that you follow best practices for security and efficiency when interacting with a database.

Let’s look at some methods below:

getInstance() -> A static method that returns the single instance of the DataBase class. If the instance does not exist, it creates one and establishes a connection to the database.
getList(string $table, string $fields, array $condition = null, string $filter = null, string $order = null, string $limit = null): ?array -> Retrieves data from the database based on the provided parameters and returns the result as an associative array.
insert(string $table, array $data): bool -> Inserts the provided data into the specified table in the database. It returns true if the operation is successful, false otherwise.
update(string $table, array $data, array $condition): bool -> Updates the specified table in the database with the provided data based on the given condition. It returns true if the operation is successful, false otherwise.
delete(string $table, array $condition): bool -> Deletes data from the specified table in the database based on the given condition. It returns true if the operation is successful, false otherwise.
              
<?php

namespace App\Models;

use Core\Database;

class User {
    private table = 'users';

    public function find($columns = '*', $conditions = null) {
        $db = Database::getInstance();

        $data = $db->getList($this->table, $columns, $conditions);

        return $data;
    }
}