PHP code example of sedalit / simple-mvc-framework
1. Go to this page and download the library: Download sedalit/simple-mvc-framework 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-mvc-framework example snippets
use App\Controllers\PostController;
// Базовые маршруты
$app->router()->get('/', [IndexController::class, 'index']);
$app->router()->post('/posts', [PostController::class, 'store']);
// Маршрут с динамическими параметрами
$app->router()->get('/posts/(?<id>\d+)', [PostController::class, 'show']);
// Маршрут с middleware
$app->router()->get('/dashboard', [DashboardController::class, 'index'], [
AuthMiddleware::class
]);
// Группа маршрутов
$app->router()->group('/admin', [
$app->router()->get('/users', [AdminController::class, 'users']),
$app->router()->get('/settings', [AdminController::class, 'settings']),
])->middleware([AuthMiddleware::class]);
namespace App\Controllers;
class PostController extends BaseController
{
public function index(): mixed
{
$posts = db()->findAll('posts');
return $this->render('posts/index', ['posts' => $posts]);
}
public function show(): mixed
{
$id = router()->routeParam('id');
$post = db()->findOrFail('posts', $id);
return $this->render('posts/show', ['post' => $post]);
}
}
namespace App\Models;
use PHPFramework\Model;
class Post extends Model
{
protected array $fillable = ['title', 'content', 'user_id'];
protected function tableName(): string
{
return 'posts';
}
protected function primaryKeyName(): string
{
return 'id';
}
}
// Использование
$post = new Post();
$post->title = 'My Post';
$post->content = 'Content here';
$id = $post->save();
$post->update();
$post->delete($id);
// В контроллере
return $this->render('posts/index', [
'title' => 'All Posts',
'posts' => $posts
]);
// В представлении (app/Views/posts/index.php)
<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
{
if (!isAdmin()) {
abort('Access denied', 403);
}
return $next();
}
}
// Установка значение
session()->set('user_id', 123);
// Получение значения
$userId = session()->get('user_id');
// Flash-сообщения
session()->setFlash('success', 'Post created!');
$message = session()->getFlash('success');
// Проверка наличия
if (session()->has('user_id')) {
// User is logged in
}
// Сохранить в кэш со сроком жизни в 1 час
cache()->set('popular_posts', $posts, 3600);
// Получить из кэша
$posts = cache()->get('popular_posts', []);
// Удалить из кэша
cache()->forget('popular_posts');
use PHPFramework\Services\Mail\Mail;
$mail = new Mail(
from: '[email protected]',
subject: 'Welcome!',
body: 'Welcome to our platform',
to: ['[email protected]']
);
App::mailer()->send($mail);
// Приложение
app() // Экземпляр Application
// View
view('template', $data, $layout) // Рендеринг view
// Request/Response
request() // Объект Request
response() // Объект Response
redirect('/path') // Редирект
// Валидация
validator() // Объект Validator
validate($data, $rules) // Быстрая валидация
// База данных
db() // Объект Database
// Сессия
session() // Объект Session
checkAuth() // Проверка авторизации
// Кэш
cache() // Объект Cache
// URL
baseUrl('/path') // Базовый URL приложения
// Безопасность
h($string) // htmlspecialchars
csrf() // CSRF token input
// Environment
env('KEY', 'default') // Получить переменную окружения
// Прочее
abort($message, $code) // Прервать выполнение с ошибкой
old('field') // Старое значение поля
formErrors('field', $errors) // Вывод ошибок валидации
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.