PHP code example of sedalit / simple-php-framework-skeleton

1. Go to this page and download the library: Download sedalit/simple-php-framework-skeleton 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/ */

    

sedalit / simple-php-framework-skeleton example snippets




use App\Controllers\IndexController;
use App\Controllers\PostController;
use PHPFramework\Middlewares\AuthMiddleware;

// Главная страница
$app->router()->get('/', [IndexController::class, 'index']);

// Статьи
$app->router()->get('/posts', [PostController::class, 'index']);
$app->router()->get('/posts/(?<id>\d+)', [PostController::class, 'show']);
$app->router()->post('/posts', [PostController::class, 'store'], [AuthMiddleware::class]);

// Админ-панель
$app->router()->group('/admin', [
    $app->router()->get('/dashboard', [AdminController::class, 'index']),
    $app->router()->get('/users', [AdminController::class, 'users']),
])->middleware([AuthMiddleware::class]);



namespace App\Controllers;

class PostController extends BaseController 
{
    public function index(): mixed
    {
        $posts = db()->table('posts')
            ->where('status', 'published')
            ->orderBy('created_at', 'DESC')
            ->get();
        
        return $this->render('posts/index', [
            'title' => 'Все статьи',
            'posts' => $posts
        ]);
    }
    
    public function show(): mixed
    {
        $id = router()->routeParam('id');
        
        $post = db()->table('posts')
            ->where('id', $id)
            ->first();
        
        if (!$post) {
            abort('Статья не найдена', 404);
        }
        
        return $this->render('posts/show', ['post' => $post]);
    }
    
    public function store(): mixed
    {
        $data = request()->post();
        
        // Валидация
        if (!validate($data, [
            'title' => '



namespace App\Models;

use PHPFramework\Model;

class Post extends Model 
{
    protected array $fillable = ['title', 'content', 'user_id', 'status'];
    
    protected function tableName(): string 
    {
        return 'posts';
    }
    
    protected function primaryKeyName(): string 
    {
        return 'id';
    }
}

<div class="container mt-4">
    <h1><?= h($title) 



namespace App\Middlewares;

use PHPFramework\Interfaces\MiddlewareInterface;
use PHPFramework\Request;
use PHPFramework\Response;

class AdminMiddleware implements MiddlewareInterface 
{
    public function handle(Request $request, Response $response, callable $next): mixed
    {
        $user = session()->get('user');
        
        if (!$user || $user['role'] !== 'admin') {
            abort('Доступ запрещен', 403);
        }
        
        return $next();
    }
}



namespace App\Validation\Rules;

use PHPFramework\Validation\ValidationRule;

class PhoneRule extends ValidationRule 
{
    protected string $message = "Поле :fieldname: должно содержать валидный номер телефона";
    
    public static function key(): ?string 
    {
        return 'phone';
    }
    
    public function passes(): bool 
    {
        return preg_match('/^\+?[1-9]\d{10,14}$/', $this->value);
    }
}

validate($data, [
    'phone' => '

const TABLES_WHITELIST = [
    'users',
    'posts',
    'comments',
    'categories'
];

public function login(): mixed
{
    if (request()->isPost()) {
        $data = request()->post();
        
        if (!validate($data, [
            'email' => ']);
        }
        
        $user = db()->table('users')
            ->where('email', $data['email'])
            ->first();
        
        if ($user && password_verify($data['password'], $user['password'])) {
            session()->set('user', $user);
            return response()->redirect('/dashboard')->send();
        }
        
        return $this->render('auth/login', [
            'error' => 'Неверные учетные данные'
        ]);
    }
    
    return $this->render('auth/login');
}

public function logout(): mixed
{
    session()->forget('user');
    return response()->redirect('/')->send();
}
nginx
server {
    listen 80;
    server_name myapp.local;
    root /path/to/my-app/public;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        
bash
php bin/console make:model Post
bash
php bin/console make:middleware AdminMiddleware
bash
php bin/console make:rule PhoneRule
bash
# Генерация файлов
php bin/console make:controller UserController
php bin/console make:model User
php bin/console make:middleware RoleMiddleware
php bin/console make:rule CustomRule

# Управление приложением
php bin/console cache:clear       # Очистить кеш
php bin/console app:setup         # Создать структуру директорий

# Помощь
php bin/console help