1. Go to this page and download the library: Download sidalex/swoole-app 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/ */
sidalex / swoole-app example snippets
declare(strict_types=1);
woole\Http\Response;
use Swoole\Http\Server;
use Swoole\Constant;
$config = json_decode(file_get_contents('./config.json'));
$http = new Server("0.0.0.0", 9501);
$http->set(
[
Constant::OPTION_WORKER_NUM => 2,
Constant::OPTION_TASK_WORKER_NUM => (swoole_cpu_num()) * 10,
]
);
$app = new \Sidalex\SwooleApp\Application($config);
$http->on(
"start",
function (Server $http) use ($app) {
echo "Swoole HTTP server is started.\n";
$app->initCyclicJobs($http);
}
);
$http->on(
"request",
function (Request $request, Response $response) use ($app,$http) {
$app->execute($request, $response,$http);
}
);
$http->on(
'task',
function (Server $server, $taskId, $reactorId, $data) use ($app) {
return $app->taskExecute($server, $taskId, $reactorId, $data);
}
);
$http->start();
use Sidalex\SwooleApp\Classes\Validators\ConfigValidatorInterface;
class DatabaseConfigValidator implements ConfigValidatorInterface
{
public function validate(\stdClass $config): void
{
if (!isset($config->DB->HOST)) {
throw new \RuntimeException("Database host
if (!$builder->validate([DatabaseConfigValidator::class])) {
$errors = $builder->getErrors();
// Handle errors
}
$http->on(
'task',
function (Server $server, $taskId, $reactorId, $data) use ($app) {
return $app->taskExecute($server, $taskId, $reactorId, $data);
}
);
Swoole\Server->task(Sidalex\SwooleApp\Classes\Tasks\Data\TaskDataInterface $data, int $dstWorkerId = -1, callable $finishCallback = null);
class MyCyclicJob implements CyclicJobsInterface
{
private $application;
private $server;
public function __construct(Application $application, Server $server)
{
$this->application = $application;
$this->server = $server;
}
public function getTimeSleepSecond(): float
{
// Returns the sleep time in seconds
return 5.0;
}
public function runJob(): void
{
$arr = [1,2,3,4,5,6,7,8,9];
foreach ($arr as $value){
if($value % 3 == 0)
{
echo "example";
}
}
}
}
#[\Sidalex\SwooleApp\Classes\Controllers\Route(uri: '/api/{v1}/get_resume',method:"POST")]
class TestController extends AbstractController
{
use Sidalex\SwooleApp\Classes\Controllers\Route;
#[Route(uri: '/api/{v1}/get_resume',method:"POST")]
class TestController extends AbstractController
{
$this->response->setHeader('Content-Type', 'application/json');
$this->response->end(
json_encode(
[
'status' => 'error',
'message' => 'collection '.$this->uri_params['collection_name'] . 'not found in collectionList',
]
)
);
class NotFoundController implements ControllerInterface
{
private \Swoole\Http\Request $request;
private \Swoole\Http\Response $responce;
/**
* @var array|string[]
*/
private array $uri_params;
public function __construct(\Swoole\Http\Request $request, \Swoole\Http\Response $response, array $uri_params=[])
{
$this->request = $request;
$this->responce = $response;
$this->uri_params = $uri_params;
}
public function execute(): \Swoole\Http\Response
{
$this->responce->setStatusCode(404);
$this->responce->setHeader('Content-Type', 'application/json');
$this->responce->end(json_encode(
[
'codeStatus' => '404',
'text' => 'Page not found'
]
));
return $this->responce;
}
public function setApplication(Application $application, Server $server)
{
}
}
namespace YourApp\StateContainers;
use Sidalex\SwooleApp\Classes\Initiation\AbstractContainerInitiator;
use Sidalex\SwooleApp\Application;
class DatabaseConnectionContainer extends AbstractContainerInitiator
{
protected string $key = 'database';
public function init(Application $app): void
{
// Initialize your database connection here
$config = $app->getConfig()->getContainer('database_config');
$this->result = new \PDO(
$config['dsn'],
$config['username'],
$config['password']
);
}
}
// In a controller:
$db = $this->application->getStateContainer()->getContainer('database');
// In a task executor:
$db = $this->app->getStateContainer()->getContainer('database');
// In a cyclic job:
$db = $this->application->getStateContainer()->getContainer('database');
declare(strict_types=1);
woole\Http\Response;
use Swoole\Http\Server;
use Swoole\Constant;
$config = json_decode(file_get_contents('./config.json'));
$http = new Server("0.0.0.0", 9501);
$http->set(
[
Constant::OPTION_WORKER_NUM => 2,
Constant::OPTION_TASK_WORKER_NUM => (swoole_cpu_num()) * 10,
]
);
$app = new \Sidalex\SwooleApp\Application($config);
$http->on(
"start",
function (Server $http) use ($app) {
echo "Swoole HTTP server is started.\n";
$app->initCyclicJobs($http);
}
);
$http->on(
"request",
function (Request $request, Response $response) use ($app,$http) {
$app->execute($request, $response,$http);
}
);
$http->on(
'task',
function (Server $server, $taskId, $reactorId, $data) use ($app) {
return $app->taskExecute($server, $taskId, $reactorId, $data);
}
);
$http->start();
use Sidalex\SwooleApp\Classes\Validators\ConfigValidatorInterface;
class DatabaseConfigValidator implements ConfigValidatorInterface
{
public function validate(\stdClass $config): void
{
if (!isset($config->DB->HOST)) {
throw new \RuntimeException("Требуется хост базы данных");
}
}
}
if (!$builder->validate([DatabaseConfigValidator::class])) {
$errors = $builder->getErrors();
// Обработка ошибок
}
$http->on(
'task',
function (Server $server, $taskId, $reactorId, $data) use ($app) {
return $app->taskExecute($server, $taskId, $reactorId, $data);
}
);
Swoole\Server->task(Sidalex\SwooleApp\Classes\Tasks\Data\TaskDataInterface $data, int $dstWorkerId = -1, callable $finishCallback = null)
class MyCyclicJob implements CyclicJobsInterface
{
private $application;
private $server;
public function __construct(Application $application, Server $server)
{
$this->application = $application;
$this->server = $server;
}
public function getTimeSleepSecond(): float
{
// Возвращает время задержки в секундах
return 5.0;
}
public function runJob(): void
{
$arr = [1,2,3,4,5,6,7,8,9];
foreach ($arr as $value){
if($value % 3 == 0)
{
echo "example";
}
}
}
}
#[\Sidalex\SwooleApp\Classes\Controllers\Route(uri: '/api/{v1}/get_resume',method:"POST")]
class TestController extends AbstractController
{
use Sidalex\SwooleApp\Classes\Controllers\Route;
#[Route(uri: '/api/{v1}/get_resume',method:"POST")]
class TestController extends AbstractController
{
$this->response->setHeader('Content-Type', 'application/json');
$this->response->end(
json_encode(
[
'status' => 'error',
'message' => 'collection '.$this->uri_params['collection_name'] . 'not found in collectionList',
]
)
);
$obj = json_decode($this->request->getContent());
class NotFoundController implements ControllerInterface
{
private \Swoole\Http\Request $request;
private \Swoole\Http\Response $responce;
/**
* @var array|string[]
*/
private array $uri_params;
public function __construct(\Swoole\Http\Request $request, \Swoole\Http\Response $response, array $uri_params=[])
{
$this->request = $request;
$this->responce = $response;
$this->uri_params = $uri_params;
}
public function execute(): \Swoole\Http\Response
{
$this->responce->setStatusCode(404);
$this->responce->setHeader('Content-Type', 'application/json');
$this->responce->end(json_encode(
[
'codeStatus' => '404',
'text' => 'Page not found'
]
));
return $this->responce;
}
public function setApplication(Application $application, Server $server)
{
}
}
namespace YourApp\StateContainers;
use Sidalex\SwooleApp\Classes\Initiation\AbstractContainerInitiator;
use Sidalex\SwooleApp\Application;
class DatabaseConnectionContainer extends AbstractContainerInitiator
{
protected string $key = 'database';
public function init(Application $app): void
{
// Инициализируйте здесь подключение к базе данных
$config = $app->getConfig()->getContainer('database_config');
$this->result = new \PDO(
$config['dsn'],
$config['username'],
$config['password']
);
}
}
// В контроллере:
$db = $this->application->getStateContainer()->getContainer('database');
// В исполнителе задач:
$db = $this->app->getStateContainer()->getContainer('database');
// В циклическом задании:
$db = $this->application->getStateContainer()->getContainer('database');
ini
SWOOLE_APP_DEBUG=true
SWOOLE_APP_DB__HOST=localhost
SWOOLE_APP_DB__PORT=3306
ini
SWOOLE_APP_DEBUG=true
SWOOLE_APP_DB__HOST=localhost
SWOOLE_APP_DB__PORT=3306
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.