### Clone Repository and Install Dependencies (Bash) Source: https://github.com/flute-cms/cms/blob/main/CONTRIBUTING.md This snippet shows the initial steps to set up the development environment by cloning the Flute CMS repository and installing its dependencies using Composer. ```bash git clone https://github.com/Flute-CMS/cms.git cd cms composer install ``` -------------------------------- ### Clone Flute CMS Repository and Install Dependencies (Bash) Source: https://github.com/flute-cms/cms/blob/main/README.md This snippet demonstrates how to clone the Flute CMS repository using Git and install its dependencies using Composer. It's the initial step for setting up the CMS locally. Ensure you have Git and Composer installed. ```bash # Clone the repository git clone https://github.com/flute-cms/cms.git # Install dependencies composer install # Follow the web installer ``` -------------------------------- ### Controller Implementation in PHP Source: https://context7.com/flute-cms/cms/llms.txt Provides examples of controller actions within Flute CMS, extending the `BaseController`. These controllers handle HTTP requests, interact with repositories (e.g., `rep('User')`), render views, and return responses (e.g., JSON or rendered HTML). Error handling and transaction management are also demonstrated. ```php findAll(); return view('users.index', [ 'users' => $users, 'title' => 'All Users' ]); } public function show(FluteRequest $request, int $id): Response { $user = rep('User')->findByPK($id); if (!$user) { return response()->error(404, 'User not found'); } return view('users.show', compact('user')); } public function store(FluteRequest $request): Response { $data = $request->input(); try { $user = new \App\Entities\User(); $user->name = $data['name']; $user->email = $data['email']; transaction($user)->run(); return response()->json([ 'success' => true, 'message' => 'User created successfully', 'data' => $user ]); } catch (\Exception $e) { logs()->error('Failed to create user', ['error' => $e->getMessage()]); return response()->json([ 'success' => false, 'message' => 'Failed to create user' ], 500); } } } ``` -------------------------------- ### Custom Middleware Creation (PHP) Source: https://context7.com/flute-cms/cms/llms.txt Provides an example of creating a custom middleware class, ApiAuthMiddleware, that implements the MiddlewareInterface for request processing in Flute CMS. It demonstrates handling authorization tokens, validating them, and attaching user information to the request. This requires the Flute Core Router component. ```php headers->get('Authorization'); if (!$token || !$this->validateToken($token)) { return response()->json([ 'error' => 'Unauthorized', 'message' => 'Invalid or missing API token' ], 401); } // Add user to request attributes $user = $this->getUserFromToken($token); $request->attributes->set('api_user', $user); return $next($request); } private function validateToken(string $token): bool { return str_starts_with($token, 'Bearer ') && strlen($token) > 20; } private function getUserFromToken(string $token): ?object { $tokenValue = substr($token, 7); return rep('ApiToken')->findOne(['token' => $tokenValue])?->user; } } // Register middleware alias in router router()->aliasMiddleware('api.auth', ApiAuthMiddleware::class); // Use in routes $router->get('/api/data', [ApiController::class, 'data']) ->middleware('api.auth'); // Middleware with parameters router()->aliasMiddleware('permission', PermissionMiddleware::class); $router->get('/admin/users', [AdminController::class, 'users']) ->middleware('permission:admin.users.view'); ``` -------------------------------- ### Implement Event System with Symfony Contracts PHP Source: https://context7.com/flute-cms/cms/llms.txt This example illustrates setting up an event system using Symfony Contracts in PHP. It covers defining custom events (e.g., UserRegisteredEvent), creating event listeners (e.g., SendWelcomeEmailListener), registering listeners in a service provider, and dispatching events from a controller. This system facilitates decoupled communication between different parts of the application. ```php user; } public function getIpAddress(): string { return $this->ipAddress; } } // Create event listener namespace App\Listeners; class SendWelcomeEmailListener { public function handle(UserRegisteredEvent $event): void { $user = $event->getUser(); try { mailer()->send('emails.welcome', [ 'user' => $user ], $user->email, 'Welcome to Our Platform'); logs()->info('Welcome email sent', ['user_id' => $user->id]); } catch (\Exception $e) { logs()->error('Failed to send welcome email', [ 'user_id' => $user->id, 'error' => $e->getMessage() ]); } } } // Register listener in service provider public function getEventListeners(): array { return [ UserRegisteredEvent::NAME => [ SendWelcomeEmailListener::class, LogUserActivityListener::class ] ]; } // Dispatch event in controller $user = $this->createUser($data); events()->dispatch( new UserRegisteredEvent($user, $request->getClientIp()), UserRegisteredEvent::NAME ); ``` -------------------------------- ### Cache Management with CacheManager (PHP) Source: https://context7.com/flute-cms/cms/llms.txt Illustrates how to manage application cache using the CacheManager class, supporting multiple drivers like Redis, Memcached, and file-based caching. It covers setting, getting, checking, deleting, and clearing cache items, along with using a helper function. Requires a PSR-3 compliant logger. ```php create([ 'driver' => 'redis', // redis, memcached, file, apcu, array 'namespace' => 'my_app', 'default_ttl' => 3600, 'redis' => [ 'host' => '127.0.0.1', 'port' => 6379 ] ]); // Store cache item $cache->set('user:1', ['name' => 'John', 'email' => 'john@example.com'], 3600); // Retrieve cache item $userData = $cache->get('user:1'); if ($userData) { echo $userData['name']; } // Check if cache exists if ($cache->has('user:1')) { // Cache exists } // Delete cache item $cache->delete('user:1'); // Clear all cache $cache->clear(); // Use helper function cache()->set('key', 'value', 3600); $value = cache()->get('key'); // Cache epoch for invalidation // Increment cache_epoch file to invalidate all cache namespaces file_put_contents(BASE_PATH . 'storage/app/cache_epoch', (int)file_get_contents(BASE_PATH . 'storage/app/cache_epoch') + 1); ``` -------------------------------- ### Define Route with Parameters and Constraints (PHP) Source: https://github.com/flute-cms/cms/blob/main/app/Core/Router/Annotations/README.md Illustrates how to define a route with a dynamic parameter and apply constraints to it using PHP 8 attributes. The `where` option in the `Get` attribute specifies a regular expression to validate the format of the `id` parameter. This ensures only numeric IDs are accepted. ```php #[Get('/users/{id}', name: 'users.show', where: ['id' => '[0-9]+'])] public function show($id) { // Show user with ID } ``` -------------------------------- ### Generate Various HTTP Responses (PHP) Source: https://context7.com/flute-cms/cms/llms.txt Provides examples for creating different types of HTTP responses using the response helper functions. This includes JSON, view, redirect, error, download, and plain text responses, along with handling HTMX partials and flash messages. Requires Symfony HttpFoundation component. ```php json([ 'success' => true, 'data' => ['id' => 1, 'name' => 'John'], 'message' => 'Operation completed' ]); // JSON response with status code return response()->json(['error' => 'Not found'], 404); // View response (render Blade template) return response()->view('users.profile', [ 'user' => $user, 'posts' => $posts ]); // Redirect response return response()->redirect('/dashboard'); return response()->redirect(url('users.show', ['id' => 1])); // Error response (renders error page) return response()->error(404, 'Page not found'); return response()->error(500, 'Internal server error'); // Download response return response()->download('/path/to/file.pdf', 'document.pdf'); // Plain text response $response = new Response('Hello World', 200); $response->headers->set('Content-Type', 'text/plain'); return $response; // HTMX partial response if ($request->isXmlHttpRequest()) { return response()->json([ 'html' => view('partials.user-card', compact('user'))->render() ]); } // Redirect with flash message flash()->success('User created successfully'); return response()->redirect('/users'); ``` -------------------------------- ### Route Registration in PHP Source: https://context7.com/flute-cms/cms/llms.txt Defines HTTP routes within the Flute CMS framework using the provided router instance. It supports basic GET, POST, and parameterized routes, route groups with middleware and prefixes, view rendering, redirects, and handling multiple HTTP methods. This enables the application to map incoming requests to specific controller actions. ```php get('/users', [UserController::class, 'index']) ->name('users.index'); // POST route with middleware $router->post('/users', [UserController::class, 'store']) ->name('users.store') ->middleware(['auth', 'csrf']); // Route with parameters $router->get('/users/{id}', [UserController::class, 'show']) ->name('users.show'); // Route groups with shared middleware and prefix $router->group(['middleware' => 'auth', 'prefix' => 'api'], function (RouterInterface $router) { $router->get('/profile', [UserController::class, 'profile']); $router->put('/profile', [UserController::class, 'update'])->middleware('csrf'); $router->delete('/profile', [UserController::class, 'destroy'])->middleware('csrf'); }); // View route (renders a view directly) $router->view('/about', 'pages.about'); // Redirect route $router->redirect('/old-page', '/new-page', 301); // Multiple HTTP methods $router->match(['GET', 'POST'], '/contact', [UserController::class, 'contact']); // All HTTP methods $router->any('/webhook', [UserController::class, 'webhook']); ``` -------------------------------- ### Define Basic Routes with PHP 8 Attributes (PHP) Source: https://github.com/flute-cms/cms/blob/main/app/Core/Router/Annotations/README.md Defines basic GET and POST routes using PHP 8 attributes on controller methods. This approach leverages annotations for concise route definitions, making route management more integrated with controller logic. It requires the Flute CMS router annotations. ```php use Flute\Core\Router\Annotations\Get; use Flute\Core\Router\Annotations\Post; use Flute\Core\Router\Annotations\Middleware; class UserController { #[Get('/users', name: 'users.index')] public function index() { // Handle GET request to /users } #[Post('/users', name: 'users.store')] #[Middleware('csrf')] public function store() { // Handle POST request to /users } } ``` -------------------------------- ### Register Attribute Routes from Directories or Classes (PHP) Source: https://github.com/flute-cms/cms/blob/main/app/Core/Router/Annotations/README.md Provides examples of how to register routes defined by PHP 8 attributes within controllers. The `router()->registerRoutesFromDirectories()` method scans a directory for controllers and registers their attribute routes, while `router()->registerRoutesFromClass()` registers routes from a single specified controller class. This requires the Flute CMS router helper function. ```php router()->registerRoutesFromDirectories([ __DIR__ . '/Controllers' ], 'Flute\Modules\Home\Controllers'); ``` ```php router()->registerRoutesFromClass('Flute\Modules\Home\Controllers\UserController'); ``` -------------------------------- ### Create Custom Service Providers for Dependency Injection (PHP) Source: https://context7.com/flute-cms/cms/llms.txt Demonstrates how to create a custom service provider by extending AbstractServiceProvider. This includes registering singleton services, initializing services after the container is built, defining event listeners, and registering the service provider in bootstrap/app.php. It leverages the Flute Core and DI components. ```php addDefinitions([ PaymentGateway::class => function (ContainerInterface $c) { return new PaymentGateway( apiKey: config('payment.api_key'), apiSecret: config('payment.api_secret'), logger: $c->get('logger') ); }, NotificationService::class => \DI\autowire() ->constructor(\DI\get('database'), \DI\get('cache')), 'payment' => \DI\get(PaymentGateway::class), ]); } public function boot(ContainerInterface $container): void { // Initialize services after container is built $paymentGateway = $container->get(PaymentGateway::class); $paymentGateway->initialize(); // Register additional routes $router = router(); $router->post('/webhooks/payment', [PaymentController::class, 'webhook']); // Register middleware aliases $router->aliasMiddleware('payment.verify', PaymentVerificationMiddleware::class); } public function getEventListeners(): array { return [ 'payment.completed' => [PaymentCompletedListener::class], 'payment.failed' => [PaymentFailedListener::class] ]; } } // Register in bootstrap/app.php $app->serviceProvider(AppServiceProvider::class); ``` -------------------------------- ### Core Application Bootstrap in PHP Source: https://context7.com/flute-cms/cms/llms.txt Initializes and runs the Flute CMS application. It sets up the base path, loads the autoloader, registers essential service providers (Database, Router, View), builds the dependency injection container, and boots the providers before running the application. This process is crucial for the CMS to function. ```php setBasePath(BASE_PATH); // Register service providers $app->serviceProvider(DatabaseServiceProvider::class) ->serviceProvider(ViewServiceProvider::class) ->serviceProvider(RouterServiceProvider::class); // Build container and boot providers $app->buildContainer(); $app->bootServiceProviders(); // Run the application $app->run(); // Application handles routing, middleware pipeline, controller execution, // and response rendering. Outputs HTTP response and executes SWR queue. ``` -------------------------------- ### PHP: Implementing a Shop Controller with Item Management and Purchase Logic Source: https://context7.com/flute-cms/cms/llms.txt This PHP code defines a controller for the 'Shop' module in Flute CMS, handling product listings, individual item views, and purchase logic. It demonstrates fetching data using a repository pattern ('rep') and interacting with user authentication and transactions. Dependencies include FluteRequest, BaseController, and repository-based data access. ```php // File: app/Modules/Shop/Controllers/ShopController.php namespace App\Modules\Shop\Controllers; use Flute\Core\Support\BaseController; class ShopController extends BaseController { public function index() { $items = rep('ShopItem')->findAll(); return view('Shop::index', compact('items')); } public function purchase(FluteRequest $request) { $itemId = $request->input('item_id'); $item = rep('ShopItem')->findByPK($itemId); if (!$item || user()->balance < $item->price) { return response()->json(['error' => 'Cannot purchase item'], 400); } // Process purchase user()->balance -= $item->price; transaction(user())->run(); return response()->json(['success' => true]); } } ``` -------------------------------- ### Database ORM Usage with Cycle ORM (PHP) Source: https://context7.com/flute-cms/cms/llms.txt Demonstrates how to define entities, query, create, update, and delete records using Cycle ORM with PHP. It also covers configuring entity auto-discovery for ORM operations. Dependencies include Cycle ORM and its annotated plugin. ```php findAll(); $user = rep('User')->findByPK(1); $user = rep('User')->findOne(['email' => 'user@example.com']); // Create and save entity $user = new User(); $user->name = 'John Doe'; $user->email = 'john@example.com'; $user->created_at = new \DateTime(); transaction($user)->run(); // Update entity $user = rep('User')->findByPK(1); $user->name = 'Jane Doe'; transaction($user)->run(); // Delete entity $user = rep('User')->findByPK(1); transaction($user, mode: 'delete')->run(); // Add entity directory for auto-discovery $db = app()->get(\Flute\Core\Database\DatabaseConnection::class); $db->addDir(BASE_PATH . 'app/Modules/MyModule/Entities'); // ORM automatically discovers entities, generates schema, and syncs with database ``` -------------------------------- ### Run All Test Suites (Bash) Source: https://github.com/flute-cms/cms/blob/main/CONTRIBUTING.md This snippet shows the command to execute all defined tests, including static analysis, code style checks, and potentially unit/integration tests, using the Composer test script. ```bash composer test ``` -------------------------------- ### PHP: Registering and Bootstrapping a Custom Module Service Provider Source: https://context7.com/flute-cms/cms/llms.txt This PHP code defines a service provider for a custom module, registering services and routes within the Flute CMS framework. It utilizes dependency injection for service registration and registers module-specific routes and entity directories during the boot process. Dependencies include Flute Core components for service providers and module management. ```php set('shop', function ($c) { return new \App\Modules\Shop\Services\ShopService( $c->get('database'), $c->get('cache') ); }); } public function boot(\Psr\Container\ContainerInterface $container): void { // Register module routes $router = router(); $router->group(['prefix' => 'shop'], function ($router) { require module_path('Shop', 'Routes/shop.php'); }); // Add entity directory $db = $container->get(\Flute\Core\Database\DatabaseConnection::class); $db->addDir(module_path('Shop', 'Entities')); } } ``` -------------------------------- ### Create Feature Branch and Push (Bash) Source: https://github.com/flute-cms/cms/blob/main/CONTRIBUTING.md This snippet demonstrates how to create a new feature branch from the 'early' branch, make changes, and push the branch to the remote repository. ```bash git checkout early git pull origin early git checkout -b feature/your-feature-name git add . git commit -m "feat: add new feature description" git push origin feature/your-feature-name ``` -------------------------------- ### Run Code Quality Checks (Bash) Source: https://github.com/flute-cms/cms/blob/main/CONTRIBUTING.md This snippet illustrates how to execute code style checks and static analysis using PHP-CS-Fixer and PHPStan, essential for maintaining code quality in Flute CMS. ```bash vendor/bin/php-cs-fixer fix --dry-run vendor/bin/phpstan analyse ``` -------------------------------- ### Run Individual Quality Checks (Bash) Source: https://github.com/flute-cms/cms/blob/main/CONTRIBUTING.md This snippet provides commands to run specific quality checks independently, such as static analysis with PHPStan, code style fixes with PHP-CS-Fixer, and migration checks. ```bash vendor/bin/phpstan analyse vendor/bin/php-cs-fixer fix --dry-run php flute migrate --dry-run ``` -------------------------------- ### Apply Middleware to Controller Methods and Classes (PHP) Source: https://github.com/flute-cms/cms/blob/main/app/Core/Router/Annotations/README.md Shows how to apply middleware to entire controller classes or specific methods using PHP 8 attributes. The `#[Middleware]` attribute can be applied at the class level for global middleware or at the method level for route-specific middleware. Multiple middleware can be applied to a single method. ```php #[Middleware('auth')] class AdminController { #[Get('/admin/settings')] #[Middleware(['permission:manage-settings', 'csrf'])] public function settings() { // Handle settings page } } ``` -------------------------------- ### PHP: Defining Module Routes for a Shop Module Source: https://context7.com/flute-cms/cms/llms.txt This PHP code defines the routes for a 'Shop' module within the Flute CMS. It sets up routes for displaying items, viewing a single item, and handling purchases, including middleware for authentication and CSRF protection. This file is typically included by the module's service provider. ```php // File: app/Modules/Shop/Routes/shop.php use App\Modules\Shop\Controllers\ShopController; $router->get('/', [ShopController::class, 'index'])->name('shop.index'); $router->get('/item/{id}', [ShopController::class, 'show'])->name('shop.item'); $router->post('/purchase', [ShopController::class, 'purchase']) ->middleware(['auth', 'csrf']) ->name('shop.purchase'); ``` -------------------------------- ### Define Route with Optional Parameter and Default Value (PHP) Source: https://github.com/flute-cms/cms/blob/main/app/Core/Router/Annotations/README.md Demonstrates defining a route with an optional parameter that has a default value using PHP 8 attributes. The `?` after `status` makes it optional, and the `defaults` attribute sets 'active' as the default if no status is provided in the URL. This simplifies handling optional route segments. ```php #[Get('/users/{status?}', name: 'users.index', defaults: ['status' => 'active'])] public function index($status) { // List users with the given status (defaults to 'active') } ``` -------------------------------- ### Generate Charts with FluteChart PHP Source: https://context7.com/flute-cms/cms/llms.txt This snippet demonstrates how to create various types of interactive charts (line, pie, bar) using the FluteChart class in PHP. It utilizes ApexCharts for rendering. The class offers methods to set chart titles, data, colors, and other visual properties. The generated chart objects can be passed to a Blade view for rendering. ```php lineChart() ->setTitle('Monthly Revenue') ->setSubtitle('2024 Performance', 'center') ->setHeight(400) ->setLabels(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']) ->setDataset([ [ 'name' => 'Revenue', 'data' => [4500, 5200, 4800, 6100, 5900, 7200] ], [ 'name' => 'Expenses', 'data' => [2100, 2300, 2200, 2800, 2600, 3100] ] ]) ->setColors(['#3b82f6', '#ef4444']) ->setGrid('#e5e5e5', 0.1) ->setMarkers() ->setStroke(3, [], 'smooth') ->setToolbar(true, true) ->setDataLabels(false); // Create pie chart $pieChart = (new FluteChart()) ->pieChart() ->setTitle('Server Distribution') ->setHeight(350) ->setLabels(['CS2', 'CS:GO', 'Minecraft', 'Other']) ->setDataset([45, 30, 15, 10]) ->setColors(['#3b82f6', '#10b981', '#f59e0b', '#ef4444']) ->setDataLabels(true); // Create bar chart with stacking $barChart = (new FluteChart()) ->barChart() ->setTitle('Player Statistics') ->setXAxis(['Server 1', 'Server 2', 'Server 3', 'Server 4']) ->setDataset([ ['name' => 'Online', 'data' => [44, 55, 41, 37]], ['name' => 'Offline', 'data' => [13, 23, 20, 8]] ]) ->setStacked(true) ->setHeight(350); // Render in Blade template // In controller: return view('dashboard', [ 'revenueChart' => $chart, 'distributionChart' => $pieChart, 'statsChart' => $barChart ]); // In Blade view: // {!! $revenueChart->cdn() !!} // {!! $revenueChart->container() !!} // {!! $revenueChart->script() !!} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.