PHP code example of dcrswoole / framework

1. Go to this page and download the library: Download dcrswoole/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/ */

    

dcrswoole / framework example snippets


use DcrSwoole\Utils\ApplicationContext;

ApplicationContext::getContainer();
//或 di();



    #[RequestMapping(methods: "GET , POST" , path:"/api/json")]
    #[Middlewares(AuthMiddleware::class , TestMiddleware::class)]
    public function test()
    {
        return 'hello';
    }


declare(strict_types=1);
namespace App\Controller;

use App\Middleware\AuthMiddleware;
use App\Middleware\TestMiddleware;
use App\Service\TestService;
use DcrSwoole\Annotation\Mapping\Middlewares;
use DcrSwoole\Annotation\Mapping\RequestMapping;
use DI\Attribute\Inject;

class MiddlewareController extends Controller
{
    #[Inject]
    public TestService $testService;
    
    #[RequestMapping(methods: "GET , POST", path:"/test/middleware")]
    #[Middlewares(AuthMiddleware::class, TestMiddleware::class)]
    public function test()
    {
        return 'hello world';
    }
}

    use App\Middleware\AuthMiddleware;
    use App\Middleware\TestMiddleware;
    use DcrSwoole\Annotation\Mapping\Middlewares;
    use DcrSwoole\Annotation\Mapping\RequestMapping;

    #[RequestMapping(methods: "GET , POST", path:"/test/middleware")]
    #[Middlewares(AuthMiddleware::class, TestMiddleware::class)]
    public function test(): string
    {
        return 'ok';
    }

use DcrSwoole\Utils\ApplicationContext;


//->all()  ->get()  ->post() 等方法
ApplicationContext::getContainer()->get(Request::class)->all();
//di()->(Request::class)->all();

use DcrSwoole\Utils\ApplicationContext;


ApplicationContext::getContainer()->get(DataRedis::class);
//->setex ->get ->del ->setnx 等方法 和predis一致



declare(strict_types=1);

namespace App\Model;

use DcrSwoole\DbConnection\Model;
/**
 * Class UserModel
 * @see https://github.com/illuminate/database
 * @property int $id
 * @property string $created_at
 */
class UserModel extends Model
{
    protected $table = 'user';
}



    #[RequestMapping(methods: "GET , POST", path:"/test/test4")]
    public function test4($request, $response)
    {
        $validate = Validation::check($this->request->post ?? [], [
            // add rule
            ['title', 'min', 40],
            ['freeTime', 'number'],
        ]);

        if ($validate->isFail()) {
            var_dump($validate->getErrors());
            var_dump($validate->firstError());
        }

        // $postData = $v->all(); // 原始数据
        $safeData = $validate->getSafeData(); // 验证通过的安全数据

        return $safeData;
    }

    #[Inject]
    public Config $config;

    #[RequestMapping(methods: "GET , POST", path:"/test/config")]
    public function config()
    {
        //di()->get(Config::class)->get('app.debug');
        return $this->config->get('app.debug');
    }


namespace App\Middleware;
use App\Middleware\Contract\MiddlewareInterface;
use DcrSwoole\Log\LogBase;
use DcrSwoole\Request\Request;
class TestMiddleware implements MiddlewareInterface
{
    public function handle()
    {
        return static function ($request, $next) {
            $data = di()->get(Request::class)->get();
//            throw new RuntimeException('test middlere error');
            return $next->handle($request);
        };
    }
}




declare(strict_types=1);

namespace App\Console\Command;

use App\Repository\TestRepository;
use DcrSwoole\Utils\ApplicationContext;
use Inhere\Console\IO\Input;
use Inhere\Console\IO\Output;
use Toolkit\PFlag\FlagsParser;

/**
 * @package app\Console\Command
 * php artisan test
 */
class TestCommand extends \Inhere\Console\Command
{
    protected static string $name = 'test';

    protected static string $desc = 'print system ENV information';

    protected function configFlags(FlagsParser $fs): void
    {
        // 绑定选项
        $fs->addOptByRule('update, up', 'bool;update linux command docs to latest');
        $fs->addOptByRule('init, i', 'bool;update linux command docs to latest');
        $fs->addOptByRule('search, s', 'string;input keywords for search');

        // 绑定参数
        // - 这里没有设置必须 可以不传,获取到就是空string
        $fs->addArg('keywords', 'the keywords for search or show docs', 'string');
    }

    protected function execute(Input $input, Output $output)
    {
        $keywords = $this->flags->getOpt('search', 23);

        ApplicationContext::getContainer()->get(TestRepository::class)->fromRepos();
        $output->info("hello world ...");
    }
}





declare(strict_types=1);

namespace App\Crontab;

use App\Crontab\Contract\CrontabInterface;
use App\Repository\TestRepository;
use DcrSwoole\Utils\ApplicationContext;

class TestCrontab implements CrontabInterface
{
    public function execute(): void
    {
        ApplicationContext::getContainer()->get(TestRepository::class)->test1();
    }
}




namespace App\Event;
use Symfony\Contracts\EventDispatcher\Event;

class TestEvent extends Event
{
    public const NAME = 'order.placed';
    //推荐使用对象 比如模型对象或dto object
    protected $params;
    public function __construct($params)
    {
        $this->params = $params;
    }
    public function getParams()
    {
        return $this->params;
    }
}




namespace App\Listener;
use App\Event\TestEvent;
use App\Listener\Contract\BaseListenerInterface;
class TestEventListener implements BaseListenerInterface
{
    /**
     * @param TestEvent $event
     */
    public function process(object $event)
    {
        echo '打印参数'.PHP_EOL;
        var_dump($event->getParams());
    }
}



    #[RequestMapping(methods: "GET , POST", path:"/test/event")]
    public function event($request, $response): array
    {
        $params = [
            'test' => 23,
        ];
        event(new TestEvent($params),TestEvent::NAME);
        // 初始化事件分发器
        return [];
    }

    #[RequestMapping(methods: "GET , POST", path:"/test/event")]
    public function event($request, $response): array
    {
        $params = [
            'test' => 23,
        ];
        $dispatcher = EventInstance::instance();
        $dispatcher->dispatch(new TestEvent($params), TestEvent::NAME);
    }


namespace App\Aspect;

use App\Service\UserService;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Hyperf\Di\Exception\Exception;

/**
 * 需要再config/config 文件配置 切面类  
 */
class DebugAspect
{
    //要切入的方法 
    public array $classes = [
        UserService::class . '::first',
    ];

    /**
     * 测试切面
     * @param ProceedingJoinPoint $proceedingJoinPoint
     * @return mixed
     */
    public function process(ProceedingJoinPoint $proceedingJoinPoint)
    {
        var_dump(11);
        try {
            return $proceedingJoinPoint->process();
        } catch (Exception $e) {
        }
    }
}


php ./bin/start.php http:start 

php ./bin/start.php ws:start 

php artisan test

/config/crontab.php  enable 改为 true 开启
shell
php migrate.php  migrations:generate
php migrate.php migrations:migrate