= htmlspecialchars($post->title) ?>
= htmlspecialchars(substr($post->content, 0, 200)) ?>...
Read more### Practical Controller Example (PHP) Source: https://context7.com/doppar/framework/llms.txt A complete controller method demonstrating the use of environment checks, authentication, caching, order creation, logging, email sending, and redirects with success messages. ```php class OrderController extends Controller { public function process(Request $request) { // Validate environment if (!env('PAYMENT_ENABLED', false)) { abort(503, 'Payment processing unavailable'); } // Check authentication if (!auth()->check()) { return redirect('/login') ->with('error', trans('messages.login_required')); } $user = auth()->user(); // Get cached data $products = cache()->stash('products', 3600, function() { return Product::query()->where('active', true)->get(); }); // Create order $order = Order::create([ 'user_id' => $user->id, 'total' => request('total'), 'items' => request('items') ]); // Log activity logger()->info('Order created', [ 'order_id' => $order->id, 'user_id' => $user->id, 'total' => $order->total ]); // Send confirmation Mail::to($user)->send(new OrderConfirmation($order)); // Redirect with message return redirect()->route('orders.show', $order->id) ->with('success', trans('messages.order.success')); } } ``` -------------------------------- ### Handling Requests and Responses (PHP) Source: https://context7.com/doppar/framework/llms.txt Illustrates how to get input from requests, retrieve multiple input fields at once, get the Request instance, and create custom responses with status codes and headers, including JSON responses. ```php // Request and Response $email = request('email'); // Get input $data = request(['name', 'email']); // Get multiple inputs $req = request(); // Get Request instance $response = response('Hello', 200, ['X-Custom' => 'value']); $json = response()->json(['data' => $users]); ``` -------------------------------- ### Create Custom Console Commands in PHP Source: https://context7.com/doppar/framework/llms.txt Demonstrates how to build custom CLI commands using the Doppar framework's `Command` class. It includes examples of defining command signatures, descriptions, handling arguments and options, and performing actions like generating reports and cleaning data. Commands are registered in `app/Console/Kernel.php` or a service provider. ```php use Phaseolies\Console\Command; class SendReportCommand extends Command { // Command signature with arguments and options protected $signature = 'report:send {user} {--type=daily} {--email=}'; // Command description protected $description = 'Send report to specified user'; // Command execution public function handle() { // Get arguments $userId = $this->argument('user'); // Get options $type = $this->option('type'); $email = $this->option('email'); // Output information $this->info("Processing report for user: {$userId}"); $this->line("Report type: {$type}"); $user = User::find($userId); if (!$user) { $this->error("User not found: {$userId}"); return 1; // Exit code 1 indicates failure } // Show progress $this->info('Generating report...'); $report = $this->generateReport($user, $type); $this->info('Sending email...'); $this->sendEmail($email ?? $user->email, $report); // Success message $this->success("Report sent successfully to {$user->email}"); // Warning example if ($type === 'weekly') { $this->warn('Weekly reports are being deprecated'); } return 0; // Exit code 0 indicates success } private function generateReport($user, $type) { // Report generation logic return ['data' => 'report content']; } private function sendEmail($email, $report) { // Email sending logic } } class CleanupCommand extends Command { protected $signature = 'cleanup:old-data {--days=30} {--force}'; protected $description = 'Clean up old data from database'; public function handle() { $days = $this->option('days'); $force = $this->option('force'); $date = now()->subDays($days); $this->info("Finding records older than {$days} days (before {$date})..."); $count = Post::query() ->where('status', 'draft') ->where('created_at', '<', $date) ->count(); $this->line("Found {$count} records to delete"); if (!$force) { $this->warn('Use --force flag to actually delete the records'); return 0; } // Delete old records Post::query() ->where('status', 'draft') ->where('created_at', '<', $date) ->delete(); $this->success("Deleted {$count} old draft posts"); return 0; } } // Register commands in app/Console/Kernel.php or service provider // $console->register(SendReportCommand::class); // $console->register(CleanupCommand::class); // Run commands: // php doppar report:send 123 --type=weekly --email=admin@example.com // php doppar cleanup:old-data --days=60 --force ``` -------------------------------- ### Translation and Session Management (PHP) Source: https://context7.com/doppar/framework/llms.txt Explains how to translate language strings with placeholders, get the translator instance, set the locale, store data in the session, retrieve session data with defaults, and use flash messages. ```php // Translation $message = trans('messages.welcome', ['name' => 'John']); $translator = lang(); lang()->setLocale('es'); // Session session()->put('key', 'value'); $value = session('key', 'default'); session()->flash('success', 'Saved!'); ``` -------------------------------- ### Date and Time Manipulation (PHP) Source: https://context7.com/doppar/framework/llms.txt Shows how to get the current timestamp as a Carbon instance, perform date/time additions, and format dates into strings. ```php // Date and time $now = now(); // Current Carbon instance $tomorrow = now()->addDay(); $formatted = now()->format('Y-m-d H:i:s'); ``` -------------------------------- ### Store and Retrieve Cached Data with PHP Source: https://context7.com/doppar/framework/llms.txt Demonstrates basic and advanced cache operations using the Phaseolies cache facade. Supports setting, getting, remembering, storing forever, adding, checking existence, deleting, and clearing cache entries. It also shows how to increment and decrement numeric cache values. This system helps improve application performance by reducing redundant computations and database queries. ```php use Phaseolies\Support\Facades\Cache; class DashboardController extends Controller { public function index() { // Basic cache operations Cache::set('site_stats', ['users' => 1000, 'posts' => 5000], 3600); // 1 hour TTL $stats = Cache::get('site_stats'); if ($stats === null) { $stats = $this->calculateStats(); Cache::set('site_stats', $stats, 3600); } // Remember pattern (fetch from cache or execute callback) $users = Cache::stash('all_users', 3600, function() { return User::query() ->where('status', 'active') ->get(); }); // Store forever (no expiration) Cache::forever('app_settings', $settings); // Add if not exists $added = Cache::add('feature_flag', true, 3600); if ($added) { // Key didn't exist, value was added } // Check if key exists if (Cache::has('user_session')) { $data = Cache::get('user_session'); } // Delete from cache Cache::delete('old_data'); Cache::forget('temporary_key'); // Alias for delete // Clear all cache Cache::clear(); return view('dashboard', compact('stats', 'users')); } public function incrementPageViews($slug) { $key = "page_views:{$slug}"; // Initialize if not exists if (!Cache::has($key)) { Cache::set($key, 0, 86400); // 24 hours } // Increment counter $views = Cache::increment($key); // Decrement also available // Cache::decrement($key); return response()->json(['views' => $views]); } } ``` -------------------------------- ### Accessing Application Container and Environment Variables (PHP) Source: https://context7.com/doppar/framework/llms.txt Demonstrates how to retrieve the application instance, resolve services from the container with or without parameters, and access environment variables with default values. ```php // Application container $app = app(); // Get Application instance $request = app('request'); // Resolve from container $db = app('db', ['connection' => 'mysql']); // With parameters // Environment variables $debug = env('APP_DEBUG', false); $dbHost = env('DB_HOST', '127.0.0.1'); ``` -------------------------------- ### Configuration Management (PHP) Source: https://context7.com/doppar/framework/llms.txt Shows how to retrieve configuration values, set configuration values dynamically, and access nested configuration options. ```php // Configuration $appName = config('app.name'); $dbConnection = config('database.default'); config(['app.timezone' => 'America/New_York']); // Set config ``` -------------------------------- ### Manage Shopping Cart with Session Data Source: https://context7.com/doppar/framework/llms.txt Handles adding items to a shopping cart, viewing the cart contents, clearing the cart, and processing checkout by interacting with session data. It utilizes session `get`, `put`, `flash`, `forget`, and `pull` methods. Product details and totals are managed within the session. ```php use Phaseolies\Support\Session; class CartController extends Controller { public function addToCart(Request $request, $productId) { $product = Product::find($productId); if (!$product) { return redirect()->back() ->with('error', 'Product not found'); } // Get existing cart from session $cart = session()->get('cart', []); // Add product to cart if (isset($cart[$productId])) { $cart[$productId]['quantity']++; } else { $cart[$productId] = [ 'name' => $product->name, 'price' => $product->price, 'quantity' => 1 ]; } // Store updated cart in session session()->put('cart', $cart); // Flash success message session()->flash('success', "Added {$product->name} to cart"); return redirect()->back(); } public function viewCart() { $cart = session()->get('cart', []); $total = 0; foreach ($cart as $item) { $total += $item['price'] * $item['quantity']; } return view('cart.index', compact('cart', 'total')); } public function clearCart() { // Remove specific session key session()->forget('cart'); return redirect()->route('cart.index') ->with('success', 'Cart cleared'); } public function checkout(Request $request) { $cart = session()->get('cart', []); if (empty($cart)) { return redirect()->route('cart.index') ->with('error', 'Your cart is empty'); } // Process order $order = $this->createOrder($cart); // Pull (get and remove) cart from session $processedCart = session()->pull('cart'); return redirect()->route('orders.show', $order->id) ->with('success', 'Order placed successfully'); } } ``` -------------------------------- ### View Rendering and Authentication (PHP) Source: https://context7.com/doppar/framework/llms.txt Demonstrates how to render views with data, pass compact data, retrieve the authenticated user, check login status, and log out the current user. ```php // Views return view('welcome', ['name' => 'John']); return view('posts.index', compact('posts')); // Authentication $user = auth()->user(); $isLoggedIn = auth()->check(); auth()->logout(); ``` -------------------------------- ### Create and Render Views using PHP Template Engine Source: https://context7.com/doppar/framework/llms.txt Demonstrates how to create and render views using a PHP-based template engine. This includes controller logic for fetching data, a layout template with sections, and specific view templates that extend the layout and define content blocks. It utilizes features like data binding, inheritance, and sections for dynamic content generation. ```php // Controller class PostController extends Controller { public function index() { $posts = Post::query() ->where('status', 'published') ->orderBy('created_at', 'DESC') ->paginate(15); return view('posts.index', [ 'posts' => $posts, 'title' => 'All Posts' ]); } public function show($id) { $post = Post::query() ->with(['author', 'comments']) ->find($id); if (!$post) { abort(404, 'Post not found'); } return view('posts.show', compact('post')); } } // Layout: resources/views/layouts/app.php
= htmlspecialchars(substr($post->content, 0, 200)) ?>...
Read moreThank you for registering with = config('app.name') ?>. We're excited to have you on board!
Please verify your email address by clicking the button below:
If you didn't create an account, please ignore this email.
Best regards,
= config('app.name') ?> Team
= trans('messages.posts.count', ['count' => $posts->count()]) ?>
``` -------------------------------- ### Group Routes with Middleware and Prefixes in Phaseolies Source: https://context7.com/doppar/framework/llms.txt Organizing related routes using `Router::group`. Allows for shared attributes like middleware, URL prefixes, and namespaces. Supports nested groups and multiple middleware. ```php // Group with prefix and middleware Router::group(['prefix' => 'admin', 'middleware' => 'auth'], function() { Router::get('/dashboard', [AdminController::class, 'dashboard']); Router::get('/users', [AdminController::class, 'users']); Router::post('/users', [AdminController::class, 'createUser']); }); // Nested groups Router::group(['prefix' => 'api/v1'], function() { Router::group(['middleware' => 'auth:api'], function() { Router::get('/user', [ApiUserController::class, 'show']); Router::put('/user', [ApiUserController::class, 'update']); }); // Public API endpoints Router::get('/posts', [ApiPostController::class, 'index']); }); // Multiple middleware Router::group(['middleware' => ['auth', 'verified', 'admin']], function() { Router::resource('/products', ProductController::class); }); ``` -------------------------------- ### Define HTTP Routes with Phaseolies Router Source: https://context7.com/doppar/framework/llms.txt Registering routes using static methods on the Router class. Supports various HTTP verbs, route parameters, named routes, and URL generation. Requires the Phaseolies namespace. ```php use Phaseolies\Support\Router; use App\Http\Controllers\UserController; use App\Http\Controllers\PostController; // Basic GET route Router::get('/users', [UserController::class, 'index']); // POST route with controller action Router::post('/users', [UserController::class, 'store']); // Route parameters Router::get('/users/{id}', [UserController::class, 'show']); Router::get('/posts/{slug}/comments/{commentId}', [PostController::class, 'showComment']); // Multiple HTTP verbs Router::match(['GET', 'POST'], '/contact', [ContactController::class, 'handle']); // Any HTTP verb Router::any('/webhook', [WebhookController::class, 'process']); // Named routes for URL generation Router::get('/profile', [ProfileController::class, 'show']) ->name('profile.show'); // Generate URL from named route $url = route('profile.show'); // Returns: /profile ``` -------------------------------- ### Build Complex SQL Queries with Query Builder Source: https://context7.com/doppar/framework/llms.txt Utilize the chainable query builder for constructing SQL queries with features like selecting/excluding columns, raw expressions, various WHERE clause operators, LIKE, BETWEEN, and joins. It supports conditional query building and automatic parameter binding. ```php use Phaseolies\Database\Entity\Query\Builder; // Select specific columns $users = User::query() ->select(['id', 'name', 'email']) ->where('status', 'active') ->get(); // Exclude columns $users = User::query() ->omit('password', 'remember_token') ->get(); // Raw select expressions $users = User::query() ->selectRaw('COUNT(*) as user_count, role') ->groupBy('role') ->get(); // WHERE clauses with operators $products = Product::query() ->where('price', '>', 100) ->where('stock', '<=', 10) ->orWhere('featured', true) ->get(); // WHERE IN and WHERE NULL $users = User::query() ->whereIn('role', ['admin', 'moderator']) ->whereNotNull('email_verified_at') ->get(); // LIKE searches $users = User::query() ->whereLike('name', '%john%', false) // Case-insensitive ->get(); // BETWEEN clause $orders = Order::query() ->whereBetween('total', [100, 500]) ->get(); // Joins $posts = Post::query() ->select(['posts.*', 'users.name as author_name']) ->join('users', 'posts.user_id', '=', 'users.id') ->where('users.status', 'active') ->get(); // Conditional queries $query = Product::query(); if ($request->has('category')) { $query->where('category', $request->category); } if ($request->has('min_price')) { $query->where('price', '>=', $request->min_price); } $products = $query->get(); // Using if() method for conditional queries $products = Product::query() ->if($request->has('category'), function($q) use ($request) { $q->where('category', $request->category); }) ->if($request->filled('search'), function($q) use ($request) { $q->whereLike('name', '%' . $request->search . '%'); }) ->get(); ``` -------------------------------- ### PHP User Authentication: Login, Logout, and Profile Source: https://context7.com/doppar/framework/llms.txt Handles user authentication, including login with credentials, session management, and logout. It supports remembering users and retrieving authenticated user details. Dependencies include the PhaseoliesAuthSecurityAuthenticate class and standard Laravel request/session handling. ```php use Phaseolies\Auth\Security\Authenticate; class AuthController extends Controller { public function login(Request $request) { $credentials = $request->only(['email', 'password']); $remember = $request->filled('remember'); // Attempt login with credentials if (auth()->try($credentials, $remember)) { // Authentication successful session()->regenerate(); // Prevent session fixation return redirect()->intended('/dashboard') ->with('success', 'Welcome back!'); } // Authentication failed return redirect()->back() ->withErrors(['email' => 'Invalid credentials']) ->withInput($request->except('password')); } public function loginWithId(Request $request) { $userId = $request->input('user_id'); // Login user by ID $user = auth()->loginUsingId($userId, true); if ($user) { return redirect('/dashboard'); } return redirect()->back()->withErrors(['error' => 'User not found']); } public function logout() { // Clear authentication session auth()->logout(); session()->invalidate(); session()->regenerateToken(); return redirect('/') ->with('success', 'Logged out successfully'); } public function profile() { // Check if user is authenticated if (!auth()->check()) { return redirect('/login') ->with('error', 'Please login to continue'); } // Get authenticated user $user = auth()->user(); $userId = auth()->id(); // Check if logged in via remember cookie $viaRemember = auth()->viaRemember(); return view('profile', [ 'user' => $user, 'viaRemember' => $viaRemember ]); } } ``` -------------------------------- ### Cache Operations (PHP) Source: https://context7.com/doppar/framework/llms.txt Shows how to set cache items with an expiration time, retrieve cached items with a default value, and remove items from the cache. ```php // Cache cache()->set('key', 'value', 3600); $value = cache('key', 'default'); cache()->forget('key'); ``` -------------------------------- ### PHP Model Hooks for Create, Update, Delete Events Source: https://context7.com/doppar/framework/llms.txt Defines hooks for various model lifecycle events in PHP. It demonstrates how to attach callback functions or class handlers to execute before or after create, update, and delete operations. Hooks can include conditional logic for execution. ```php use Phaseolies\Database\Entity\Model; class User extends Model { protected $creatable = ['name', 'email', 'password']; // Define hooks array protected $hooks = [ 'before_created' => [ 'handler' => function($model) { // Generate UUID before creating $model->uuid = \Ramsey\Uuid\Uuid::uuid4()->toString(); // Hash password if not already hashed if (!password_get_info($model->password)['algo']) { $model->password = password_hash($model->password, PASSWORD_BCRYPT); } }, 'when' => true // Always run ], 'after_created' => [ 'handler' => CreateUserProfile::class, 'when' => true ], 'before_updated' => [ 'handler' => function($model) { // Log changes logger()->info('User updated', [ 'user_id' => $model->id, 'changes' => $model->getDirty() ]); }, 'when' => function($model) { // Only run if specific fields changed return $model->isDirty(['name', 'email']); } ], 'after_updated' => ClearUserCache::class, 'before_deleted' => [ 'handler' => function($model) { // Delete related records $model->posts()->delete(); $model->comments()->delete(); }, 'when' => function($model) { return $model->posts()->count() > 0 || $model->comments()->count() > 0; } ], 'after_deleted' => NotifyAdminOfDeletion::class ]; public function posts() { return $this->linkMany(Post::class, 'user_id', 'id'); } public function comments() { return $this->linkMany(Comment::class, 'user_id', 'id'); } } // Hook handler class class CreateUserProfile { public function handle(Model $user) { Profile::create([ 'user_id' => $user->id, 'bio' => '', 'avatar' => 'default-avatar.png' ]); // Send welcome email Mail::to($user)->send(new WelcomeMail($user)); } } class ClearUserCache { public function handle(Model $user) { Cache::forget('user:' . $user->id); Cache::forget('user:profile:' . $user->id); Cache::forget('user:posts:' . $user->id); } } class NotifyAdminOfDeletion { public function handle(Model $user) { $admins = User::query()->where('role', 'admin')->get(); foreach ($admins as $admin) { Mail::to($admin)->send(new UserDeletedNotification($user)); } } } // Usage class UserController extends Controller { public function store(Request $request) { // Hooks fire automatically $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => $request->password // Will be hashed by before_created hook ]); // after_created hook creates profile and sends email return redirect()->route('users.show', $user->id); } public function update(Request $request, $id) { $user = User::find($id); // before_updated logs changes, after_updated clears cache $user->update($request->only(['name', 'email'])); return redirect()->back()->with('success', 'User updated'); } public function delete($id) { $user = User::find($id); // before_deleted removes related records, after_deleted notifies admins $user->delete(); return redirect()->route('users.index')->with('success', 'User deleted'); } public function updateWithoutHooks($id) { // Disable hooks for this operation $user = User::withoutHook()->find($id); $user->update(['last_login' => now()]); // No hooks will fire } } ```
Comments (= $post->comments->count() ?>)
comments as $comment):= htmlspecialchars($comment->author->name) ?>
= htmlspecialchars($comment->content) ?>
= $comment->created_at->diffForHumans() ?>