### Install and Start EasySwoole Source: https://context7.com/easy-swoole/easyswoole/llms.txt Commands to install EasySwoole via Composer, initialize the project, and manage the server lifecycle. ```bash composer require easyswoole/easyswoole=3.7.x ``` ```bash php vendor/bin/easyswoole.php install ``` ```bash php easyswoole.php server start ``` ```bash php easyswoole.php server start -d ``` ```bash php easyswoole.php server stop ``` ```bash php easyswoole.php server stop -force ``` ```bash php easyswoole.php server reload ``` ```bash php easyswoole.php server restart ``` ```bash php easyswoole.php server status ``` ```bash php easyswoole.php server start -mode=produce ``` -------------------------------- ### EasySwoole Installation Source: https://github.com/easy-swoole/easyswoole/blob/3.x/README.md Commands to install EasySwoole using Composer and start the server. Ensure you have Composer installed. ```bash composer require easyswoole/easyswoole=3.7.x php vendor/bin/easyswoole.php install php easyswoole.php server start ``` -------------------------------- ### Run EasySwoole Container with Docker Source: https://context7.com/easy-swoole/easyswoole/llms.txt Commands to pull the official EasySwoole Docker image, run a container, and set up the application inside it. Includes steps for composer installation and starting the server. ```bash # Pull the official Docker image docker pull easyswoolexuesi2021/easyswoole:php8.1.22-alpine3.16-swoole4.8.13 # Run the container docker run --name easyswoole \ -v /workspace/project:/var/www/project \ -p 9501:9501 \ -it \ --privileged \ -u root \ --entrypoint /bin/sh \ easyswoolexuesi2021/easyswoole:php8.1.22-alpine3.16-swoole4.8.13 # Inside the container, set up and start EasySwoole cd /var/www/project composer require easyswoole/easyswoole=3.7.x php vendor/bin/easyswoole.php install php easyswoole.php server start -d ``` -------------------------------- ### Production Dockerfile for EasySwoole Source: https://context7.com/easy-swoole/easyswoole/llms.txt A sample Dockerfile for deploying EasySwoole applications in production. It uses the official image, copies application files, installs dependencies, exposes the port, and sets the start command. ```dockerfile # Dockerfile example for production FROM easyswoolexuesi2021/easyswoole:php8.1.22-alpine3.16-swoole4.8.13 WORKDIR /var/www # Copy application files COPY . . # Install dependencies RUN composer install --no-dev --optimize-autoloader # Expose the default port EXPOSE 9501 # Start the server CMD ["php", "easyswoole.php", "server", "start"] ``` -------------------------------- ### Configuration Management with Config Class Source: https://context7.com/easy-swoole/easyswoole/llms.txt Demonstrates how to use the Config class for managing application settings, including getting, setting, and loading configurations from various sources. ```php getConf('MAIN_SERVER.PORT'); // Returns: 9501 // Get the entire configuration as an array $allConfig = Config::getInstance()->getConf(); // Set a configuration value Config::getInstance()->setConf('MAIN_SERVER.PORT', 9502); // Set nested configuration Config::getInstance()->setConf('MAIN_SERVER.SETTING.worker_num', 16); // Load configuration from a PHP file that returns an array Config::getInstance()->loadFile('/path/to/custom_config.php'); // Load and merge configuration (default behavior) Config::getInstance()->loadFile('/path/to/extra_config.php', true); // Load configuration without merging (replace) Config::getInstance()->loadFile('/path/to/config.php', false); // Load all configuration files from a directory Config::getInstance()->loadDir('/path/to/config_directory/', true); // Load configuration from .env INI file Config::getInstance()->loadEnv('/path/to/.env', true); // Merge additional configuration array Config::getInstance()->merge([ 'CUSTOM_KEY' => 'value', 'DATABASE' => [ 'host' => 'localhost', 'port' => 3306 ] ]); // Clear all configuration Config::getInstance()->clear(); // Get the configuration array $configArray = Config::getInstance()->toArray(); ``` -------------------------------- ### Basic HTTP Controller in EasySwoole Source: https://github.com/easy-swoole/easyswoole/blob/3.x/README.md A simple controller that responds with 'Hello World'. This is a foundational example for handling HTTP requests. ```php response()->write('Hello World'); } } ``` -------------------------------- ### Default Development Configuration Structure Source: https://context7.com/easy-swoole/easyswoole/llms.txt An example of a default development configuration file (dev.php) for EasySwoole, outlining server settings, logging, and temporary directory configurations. ```php "EasySwoole", 'MAIN_SERVER' => [ 'LISTEN_ADDRESS' => '0.0.0.0', 'PORT' => 9501, // Server types: EASYSWOOLE_SERVER, EASYSWOOLE_WEB_SERVER, EASYSWOOLE_WEB_SOCKET_SERVER 'SERVER_TYPE' => EASYSWOOLE_WEB_SERVER, 'SOCK_TYPE' => SWOOLE_TCP, 'RUN_MODEL' => SWOOLE_PROCESS, 'SETTING' => [ 'worker_num' => 8, 'reload_async' => true, 'max_wait_time' => 3, 'enable_deadlock_check' => false, 'daemonize' => false, 'pid_file' => '/var/run/easyswoole.pid', 'log_file' => '/var/log/easyswoole.log' ], 'TASK' => [ 'workerNum' => 4, 'maxRunningNum' => 128, 'timeout' => 15 ] ], "LOG" => [ 'dir' => '/var/log/easyswoole', 'level' => LoggerInterface::LOG_LEVEL_DEBUG, 'handler' => null, 'logConsole' => true, 'displayConsole' => true, 'ignoreCategory' => [] ], 'TEMP_DIR' => '/tmp/easyswoole' ]; ``` -------------------------------- ### Running EasySwoole in Docker Source: https://github.com/easy-swoole/easyswoole/blob/3.x/README.md Command to run an EasySwoole Docker container, mapping a local project directory and exposing port 9501. This setup is useful for development. ```bash docker run --name easyswoole \ -v /workspace/project:/var/www/project \ -p 9501:9501 -it \ --privileged -u root \ --entrypoint /bin/sh \ easyswoolexuesi2021/easyswoole:php8.1.22-alpine3.16-swoole4.8.13 ``` -------------------------------- ### Manage Dependencies with EasySwoole DI Container Source: https://context7.com/easy-swoole/easyswoole/llms.txt Utilize the Di container to set, get, delete, and clear values, including singletons and system constants. Useful for managing application-wide configurations and services. ```php set('database.config', [ 'host' => 'localhost', 'port' => 3306, 'database' => 'myapp' ]); // Get a value from the container $dbConfig = Di::getInstance()->get('database.config'); // Set a singleton service Di::getInstance()->set('cache', function () { return new Redis(); }); // System constants for common DI keys Di::getInstance()->set(SysConst::LOGGER_HANDLER, $customLogger); Di::getInstance()->set(SysConst::ERROR_HANDLER, function ($errorCode, $description, $file, $line) { // Custom error handling }); Di::getInstance()->set(SysConst::TRIGGER_HANDLER, $customTrigger); Di::getInstance()->set(SysConst::HTTP_CONTROLLER_NAMESPACE, 'App\\HttpController\\'); Di::getInstance()->set(SysConst::HTTP_CONTROLLER_MAX_DEPTH, 5); Di::getInstance()->set(SysConst::HTTP_CONTROLLER_POOL_MAX_NUM, 500); Di::getInstance()->set(SysConst::HTTP_CONTROLLER_POOL_WAIT_TIME, 5); Di::getInstance()->set(SysConst::HTTP_EXCEPTION_HANDLER, function ($throwable, $request, $response) { $response->withStatus(500); $response->write(json_encode(['error' => $throwable->getMessage()])); }); Di::getInstance()->set(SysConst::HTTP_GLOBAL_ON_REQUEST, function ($request, $response) { // Global request middleware return true; }); Di::getInstance()->set(SysConst::HTTP_GLOBAL_AFTER_REQUEST, function ($request, $response) { // Global after-request hook }); Di::getInstance()->set(SysConst::SHUTDOWN_FUNCTION, function () { // Custom shutdown handler }); Di::getInstance()->set(SysConst::ERROR_REPORT_LEVEL, E_ALL); // Delete a value Di::getInstance()->delete('cache'); // Clear all values Di::getInstance()->clear(); ``` -------------------------------- ### Registering Swoole Server Events with EventHelper Source: https://context7.com/easy-swoole/easyswoole/llms.txt Demonstrates various methods for registering callbacks to Swoole server events using EventHelper and the EventRegister object. Use EventHelper::register to replace existing callbacks and EventHelper::registerWithAdd to add multiple callbacks for the same event. ```php getSwooleServer(); EventHelper::on($server, 'start', function ($server) { echo "Master process PID: {$server->master_pid}\n"; }); // Using register object directly $register->set(EventRegister::onManagerStart, function ($server) { echo "Manager process started\n"; }); $register->add(EventRegister::onWorkerStop, function ($server, $workerId) { echo "Worker {$workerId} stopping\n"; }); // Get all registered callbacks for an event $callbacks = $register->all(); } ``` -------------------------------- ### Asynchronous and Synchronous Task Execution with EasySwoole TaskManager Source: https://context7.com/easy-swoole/easyswoole/llms.txt Shows how to define a task class implementing TaskInterface and use TaskManager for async (fire-and-forget, with callback) and sync task execution. Also demonstrates using closures as tasks. ```php email = $email; $this->subject = $subject; $this->content = $content; } public function run(int $taskId, int $workerIndex) { // Execute the task // mail($this->email, $this->subject, $this->content); return [ 'success' => true, 'email' => $this->email, 'taskId' => $taskId ]; } public function onException(\Throwable $throwable, int $taskId, int $workerIndex) { // Handle task exceptions Trigger::getInstance()->throwable($throwable); } } // In a controller or anywhere in worker process class MailController extends Controller { public function send() { $email = $this->request()->getParsedBody('email'); $subject = $this->request()->getParsedBody('subject'); $content = $this->request()->getParsedBody('content'); // Async task (fire and forget) TaskManager::getInstance()->async(new SendEmailTask($email, $subject, $content)); // Async task with callback TaskManager::getInstance()->async( new SendEmailTask($email, $subject, $content), function ($reply, $taskId) { // Called when task completes Logger::getInstance()->info("Task {$taskId} completed: " . json_encode($reply)); } ); // Sync task (blocks until complete, with timeout) $result = TaskManager::getInstance()->sync( new SendEmailTask($email, $subject, $content), 5.0 // Timeout in seconds ); // Using closure as task TaskManager::getInstance()->async(function ($taskId, $workerIndex) use ($email) { // Task logic here return "Sent email to {$email}"; }); $this->response()->write(json_encode(['message' => 'Email queued'])); } } ``` -------------------------------- ### Using EasySwoole Logger for Different Log Levels Source: https://context7.com/easy-swoole/easyswoole/llms.txt Shows how to instantiate and use the Logger class for various logging levels like debug, info, warning, and error. Custom log categories and levels can also be specified. ```php debug('Debug message', 'debug'); $logger->info('Info message', 'info'); $logger->notice('Notice message', 'notice'); $logger->warning('Warning message', 'warning'); $logger->error('Error message', 'error'); // Generic log with custom level $logger->log('Custom message', LoggerInterface::LOG_LEVEL_INFO, 'custom-category'); // Console output only (no file logging) $logger->console('Console only message', LoggerInterface::LOG_LEVEL_DEBUG, 'console'); // Configure log level (only logs at or above this level are recorded) $logger->logLevel(LoggerInterface::LOG_LEVEL_WARNING); // Enable/disable console logging $logger->logConsole(true); // Enable $logger->logConsole(false); // Disable // Enable/disable console display $logger->displayConsole(true); // Ignore specific categories $logger->ignoreCategory(['debug', 'trace']); // Register callback for log events $logger->onLog()->set('custom_handler', function ($msg, $logLevel, $category) { // Send to external logging service // e.g., send to ELK stack, Sentry, etc. }); // Log levels available: // LoggerInterface::LOG_LEVEL_DEBUG = 1 // LoggerInterface::LOG_LEVEL_INFO = 2 // LoggerInterface::LOG_LEVEL_NOTICE = 3 // LoggerInterface::LOG_LEVEL_WARNING = 4 // LoggerInterface::LOG_LEVEL_ERROR = 5 ``` -------------------------------- ### Initialize EasySwoole Application Source: https://context7.com/easy-swoole/easyswoole/llms.txt Implement the initialize method to set up application-wide configurations such as timezone, DI, error reporting, and global request/response hooks. This method is called during framework initialization. ```php set(SysConst::HTTP_CONTROLLER_NAMESPACE, 'App\\HttpController\\'); // Set maximum controller depth Di::getInstance()->set(SysConst::HTTP_CONTROLLER_MAX_DEPTH, 5); // Set custom error reporting level Di::getInstance()->set(SysConst::ERROR_REPORT_LEVEL, E_ALL); // Set global HTTP request hook (return false to stop request processing) Di::getInstance()->set(SysConst::HTTP_GLOBAL_ON_REQUEST, function ($request, $response) { // Add CORS headers $response->withHeader('Access-Control-Allow-Origin', '*'); return true; // Continue processing }); // Set global after-request hook Di::getInstance()->set(SysConst::HTTP_GLOBAL_AFTER_REQUEST, function ($request, $response) { // Log request completion }); // Set custom HTTP exception handler Di::getInstance()->set(SysConst::HTTP_EXCEPTION_HANDLER, function ($throwable, $request, $response) { $response->withStatus(500); $response->write(json_encode([ 'error' => $throwable->getMessage(), 'code' => $throwable->getCode() ])); }); } /** * Called after the main server is created * Use this for registering server events, adding sub-servers, etc. */ public static function mainServerCreate(EventRegister $register) { // Register worker start callback $register->add(EventRegister::onWorkerStart, function ($server, $workerId) { // Initialize connections, caches, etc. per worker echo "Worker {$workerId} started\n"; }); // Register custom event on server start $register->add(EventRegister::onStart, function ($server) { echo "Server started on port " . $server->port . "\n"; }); } } ``` -------------------------------- ### Add and Configure TCP and WebSocket Sub-Servers Source: https://context7.com/easy-swoole/easyswoole/llms.txt Use ServerManager to add TCP and WebSocket sub-servers with custom configurations and event handlers. Ensure the main server is created before adding sub-servers. ```php getSwooleServer(); // Get server configuration $workerNum = $swooleServer->setting['worker_num']; // Add a TCP sub-server on port 9502 $tcpServer = ServerManager::getInstance()->addServer( 'tcp', // Server name 9502, // Port SWOOLE_TCP, // Socket type '0.0.0.0', // Listen address [ 'open_length_check' => true, 'package_max_length' => 1024 * 1024 * 2, 'package_length_type' => 'N', 'package_length_offset' => 0, 'package_body_offset' => 4, ] ); // Register TCP server events $tcpServer->set(EventRegister::onReceive, function ($server, $fd, $reactorId, $data) { $server->send($fd, "Received: " . $data); }); $tcpServer->set(EventRegister::onConnect, function ($server, $fd) { echo "Client {$fd} connected\n"; }); $tcpServer->set(EventRegister::onClose, function ($server, $fd) { echo "Client {$fd} closed\n"; }); // Add a WebSocket sub-server $wsServer = ServerManager::getInstance()->addServer( 'websocket', 9503, SWOOLE_SOCK_TCP, '0.0.0.0' ); $wsServer->set(EventRegister::onMessage, function ($server, $frame) { $server->push($frame->fd, "Echo: " . $frame->data); }); $wsServer->set(EventRegister::onOpen, function ($server, $request) { echo "WebSocket connection opened: {$request->fd}\n"; }); // Get the main event register $mainRegister = ServerManager::getInstance()->getEventRegister(); // Get a sub-server event register $tcpRegister = ServerManager::getInstance()->getEventRegister('tcp'); // Get a specific sub-server $tcpPort = ServerManager::getInstance()->getSwooleServer('tcp'); // Check if server is running $isRunning = ServerManager::getInstance()->isStart(); } ``` -------------------------------- ### Logging Errors and Throwables with EasySwoole Trigger Source: https://context7.com/easy-swoole/easyswoole/llms.txt Demonstrates logging errors with and without explicit location information, and handling throwables. Includes registering custom callbacks for error and exception events. ```php setFile(__FILE__); $location->setLine(__LINE__); Trigger::getInstance()->error('Custom error message', E_USER_ERROR, $location); // Log an error (auto-detects location) Trigger::getInstance()->error('An error occurred', E_USER_WARNING); // Log a throwable (exception) try { throw new \Exception('Something went wrong'); } catch (\Throwable $e) { Trigger::getInstance()->throwable($e); } // Register callback for error events Trigger::getInstance()->onError()->set('error_handler', function ($msg, $errorCode, $location) { // Custom error handling // Send notification, log to database, etc. error_log("Error [{$errorCode}]: {$msg} in {$location->getFile()}:{$location->getLine()}"); }); // Register callback for exception events Trigger::getInstance()->onException()->set('exception_handler', function (\Throwable $throwable) { // Custom exception handling error_log("Exception: " . $throwable->getMessage()); error_log("Stack trace: " . $throwable->getTraceAsString()); }); ``` -------------------------------- ### Basic HTTP Controller Structure Source: https://context7.com/easy-swoole/easyswoole/llms.txt Define RESTful controllers by extending the base Controller class. Automatic routing is based on namespace structure. Implement methods like index, info, and create to handle different HTTP requests. ```php response()->write(json_encode([ 'users' => [ ['id' => 1, 'name' => 'John'], ['id' => 2, 'name' => 'Jane'] ] ])); } /** * GET /user/info?id=1 * POST /user/info with body id=1 */ public function info() { // Get query parameter $id = $this->request()->getQueryParam('id'); // Get POST parameter $name = $this->request()->getParsedBody('name'); // Get request method $method = $this->request()->getMethod(); // Get all parameters $params = $this->request()->getRequestParam(); // Set response content type $this->response()->withHeader('Content-Type', 'application/json'); $this->response()->write(json_encode([ 'id' => $id, 'name' => $name ?? 'Unknown', 'method' => $method ])); } /** * POST /user/create */ public function create() { $body = $this->request()->getParsedBody(); // Validate input if (empty($body['name'])) { $this->response()->withStatus(400); $this->response()->write(json_encode(['error' => 'Name is required'])); return; } $this->response()->withStatus(201); $this->response()->write(json_encode([ 'message' => 'User created', 'data' => $body ])); } /** * Handle action not found */ protected function actionNotFound(?string $action) { $this->response()->withStatus(404); $this->response()->write(json_encode([ 'error' => "Action '{$action}' not found" ])); } /** * Called before action execution * Return false to prevent action execution */ protected function onRequest(?string $action): ?bool { // Authentication check $token = $this->request()->getHeader('authorization'); if (empty($token) && $action !== 'login') { $this->response()->withStatus(401); $this->response()->write(json_encode(['error' => 'Unauthorized'])); return false; } return true; } /** * Called after action execution */ protected function afterAction(?string $actionName): void { // Cleanup or logging } } ``` -------------------------------- ### Define and Register a Cron Job in PHP Source: https://context7.com/easy-swoole/easyswoole/llms.txt Implement the JobInterface to define a cron job's schedule and execution logic. Register jobs within EasySwooleEvent::mainServerCreate(). ```php throwable($throwable); } } // Register cron jobs in EasySwooleEvent::mainServerCreate() public static function mainServerCreate(EventRegister $register) { // Register a job class Crontab::getInstance()->register(new CleanupJob()); // Cron expression examples: // '* * * * *' - Every minute // '*/5 * * * *' - Every 5 minutes // '0 * * * *' - Every hour // '0 0 * * *' - Every day at midnight // '0 0 * * 0' - Every Sunday at midnight // '0 0 1 * *' - First day of every month // '0 0 1 1 *' - Every year on January 1st } ``` -------------------------------- ### Docker Image Pull Source: https://github.com/easy-swoole/easyswoole/blob/3.x/README.md Command to pull a pre-built EasySwoole Docker image. This image is based on PHP 8.1.22, Alpine 3.16, and Swoole 4.8.13. ```bash docker pull easyswoolexuesi2021/easyswoole:php8.1.22-alpine3.16-swoole4.8.13 ``` -------------------------------- ### Custom Routing with FastRoute Source: https://context7.com/easy-swoole/easyswoole/llms.txt Define custom routes using FastRoute integration. Supports basic route mapping, closures, RESTful API routes, route groups with prefixes, and handling multiple HTTP methods. ```php Index controller, test action $routeCollector->get('/router', '/test'); // Route with closure handler $routeCollector->get('/closure', function (Request $request, Response $response) { $response->write('This is a closure router'); return false; // Don't continue to controller parsing }); // RESTful routes $routeCollector->get('/api/users', '/Api/User/list'); $routeCollector->get('/api/users/{id:\d+}', '/Api/User/info'); $routeCollector->post('/api/users', '/Api/User/create'); $routeCollector->put('/api/users/{id:\d+}', '/Api/User/update'); $routeCollector->delete('/api/users/{id:\d+}', '/Api/User/delete'); // Route group with prefix $routeCollector->addGroup('/admin', function (RouteCollector $collector) { $collector->get('/dashboard', '/Admin/Index/dashboard'); $collector->get('/settings', '/Admin/Index/settings'); }); // Multiple HTTP methods $routeCollector->addRoute(['GET', 'POST'], '/form', '/Form/handle'); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.