PHP code example of richie314 / simple-mvc

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

    

richie314 / simple-mvc example snippets



// HomeController.php
use Richie314\SimpleMvc\Controllers\Controller;
use Richie314\SimpleMvc\Http\StatusCode;

class HomeController extends Controller
{
    public function index(string $name = 'World'): StatusCode
    {
        return $this->Render('Home/index', ['name' => $name], 'Welcome');
    }

    public function hello(string $first_name = 'World'): StatusCode
    {
        return $this->Json(['hello' => $first_name]);
    }
}


// index.php
'/HomeController.php';

use Richie314\SimpleMvc\Routers\Router;

$router = new Router(applicationInstallationPath: __DIR__);
$router->SetDefaultVariable('siteName', 'My application');
$router->AddController(HomeController::class, '/');
$router->Dispatch($_SERVER['REQUEST_URI']);

<!-- Views/Shared/Layout.php -->
<!doctype html>
<html lang="en">
<title><?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') 

<!-- Views/Home/index.php -->
<h1>Hello <?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') 

$router->AddRouteAction('/welcome', HomeController::class, 'index');

return $this->Content('text/plain', 'Saved');
return $this->Json(['id' => 42], StatusCode::Created);
return $this->JsonWithOptions(['url' => '/items/42'], flags: JSON_UNESCAPED_SLASHES);
return $this->RedirectWithStatus('/items/42', StatusCode::SeeOther);
return $this->File('/absolute/path/report.pdf'); // attachment by default

use Richie314\SimpleMvc\Users\User;

$user = new User();
$user->Id = 123;
$user->Name = 'Ada';
$user->Admin = false;
$router->SetUser($user);
// Optional: $router->SetDbConnection($mysqli);

use Richie314\SimpleMvc\Http\StatusCode;
use Richie314\SimpleMvc\Controllers\Attributes\RequireLogin;

#[RequireLogin(loginPath: '/login')]
public function account(): StatusCode
{
    return $this->Json(['name' => $this->User->Name]);
}

use Richie314\SimpleMvc\Utils\Cookie;
use Richie314\SimpleMvc\Utils\Security;

$hash = Security::Hash('a password');
$matches = Security::TestPassword('a password', $hash);

// Reads $_ENV['DB_PASSWORD'], otherwise the file in $_ENV['DB_PASSWORD_FILE'].
// File contents are returned verbatim, including empty strings and trailing newlines.
$password = Security::LoadEnvironmentOfFromFile('DB_PASSWORD', 'fallback');

Cookie::SetWithOptions('session_hint', 'value', 3600, path: '/myapp', secure: true, sameSite: 'Lax');
$value = Cookie::Get('session_hint'); // null when absent
Cookie::DeleteWithOptions('session_hint', path: '/myapp'); // match the original path and domain
text
app/
  index.php
  HomeController.php
  Views/
    Home/index.php
    Shared/Layout.php
  vendor/