PHP code example of icesoft / lark

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

    

icesoft / lark example snippets



use Lark\Routing\BaseController;

use Lark\Annotation\Controller;
use Lark\Annotation\Route;
use Lark\Annotation\Response;
use Lark\Annotation\InjectService;
/**
 * Class TestController
 * @package Controller
 * @Controller(path="/test")
 * @Bean
 */
class TestController extends BaseController
{
    /**
     * @var UserService
     * @InjectService           #该注入自动注入一个Proxy类, 对应变量名为相对应服务, 具体可以参考服务
     */
    private $UserService;

    /**
     * @Route(path="/index")
     * @Response(type="json")
     */
    public function index() {
        $key = $this->UserService->create('menmen_' . mt_rand(1, 20), mt_rand(14, 100));

        return ['code' => 400, 'insertId' => $key];
    }

    /**
     * @Route(path="/test")
     * @Response(type="template", data="index")  #index代表模板文件, 返回值对应模板中的变量
     */
    public function test()
    {
        return [];
    }
}


use Lark\Annotation\Bean;
use Lark\Annotation\InjectService;
use Lark\Command\Command;
use Lark\Command\CommandDescribe;

/**
 * Class DemoCommand
 * @package App\Commands
 * @Bean
 */
class DemoCommand extends Command
{
    /**
     * @var UserService
     * @InjectService
     */
    private $UserService;

    public function registry(): CommandDescribe
    {
        return new CommandDescribe('test', 'demo', 'This is test:demo command');
    }

    public function execute()
    {
        $this->line("test demo mesdsasge");
        $this->block('Test Demo command', ['this is info', ' sdfghsdfh']);
        
        return 1;
    }
}


use App\Entitys\UserEntity;
use Lark\Annotation\Bean;

/**
 * User Service
 * @package App\Services
 * @Bean
 */
class UserService
{
    /**
     * 查找用户数据
     */
    public function get($id)
    {
        return UserEntity::find($id);
    }

    /**
     * 创建用户
     */
    public function create($name, $age, $enable=1)
    {
        $user = new UserEntity();
        $user->setName($name);
        $user->setEnable($enable);
        $user->setAge($age);
        $user->setCreated(time());

        return $user->save();
    }
}


namespace App\Listeners\Event;

use Lark\Event\Event;

/**
 * Class UserRegisteredEvent
 * @package App\Listeners\Event
 */
class UserRegisteredEvent implements Event
{
    private $user;

    /**
     * UserRegisteredEvent constructor.
     * @param $user
     */
    public function __construct($user)
    {
        $this->user = $user;
    }

    /**
     * @return mixed
     */
    public function getUser()
    {
        return $this->user;
    }

    public function getName()
    {
        return 'UserLogin';
    }
}


namespace App\Listeners;


use App\Listeners\Event\UserRegisteredEvent;
use Lark\Event\EventManager;
use Lark\Event\Listener;
use Swoole\Coroutine;


/**
 * Class UserRegisteredListener
 * @package App\Listeners
 */
class UserRegisteredListener implements Listener
{

    public function listen(): array
    {
        return [
            UserRegisteredEvent::class
        ];
    }

    public function process($event)
    {
//        Coroutine::sleep(2);
        var_dump('用户登录触发主事件', $event);
    }
}


/**
 * 系统需要监听的事件在此配置
 */
return [
    \App\Listeners\UserRegisteredEvent::class,
];

EventManager::Instance()->trigger(new UserLoginEvent(['id' => 200, 'name'=>'test', ...]));


namespace App\Middlewares;

use App\Components\JWT\JWTException;
use App\Components\JWT\JwtHandle;
use App\Exceptions\InterfaceException;
use Lark\Middleware\Middleware;
use Lark\Routing\Request;
use Lark\Routing\Response;


/**
 * JWT Middleware
 * @package Middleware
 */
class AuthMiddleware extends Middleware
{
    const DISABLE_URI = [
        '/call/test4',
        '/demo/(.*)',
        '/logger/(.*)'
    ];

    /**
     * @param string $request_uri
     * @return bool
     */
    private function check_request_uri(string $request_uri): bool
    {
        $is_check = false;
        foreach (AuthMiddleware::DISABLE_URI as $pattern) {
            if (preg_match("#^/?" . $pattern . "/?$#", $request_uri, $match)) {
                if ($pattern == $request_uri) {
                    $is_check = true;
                    break;
                } else {
                    $is_check = true;
                    continue;
                }
            }
        }

        return $is_check;
    }

    /**
     * @param Request $request
     * @param Response $response
     * @return mixed|void
     * @throws InterfaceException
     */
    public function handle(Request $request, Response $response)
    {
        $request_uri = $request->server('request_uri');
        if (!$this->check_request_uri($request_uri)) {
            $token =  $request->header('authorization');
            try {
                $result = (array)JwtHandle::getInstance()->valid_token($token);
                if ($result['exp'] - time() > 600) {
                    $new_token = JwtHandle::getInstance()->refresh_token($result);
                    $response->header('jwt_token', $new_token, false);
                }
            } catch(JWTException $ex) {
                throw new InterfaceException(InterfaceException::JWT_TOKEN_EXCEPTION);
            }
        }
    }
}


namespace App\Exceptions;

use Lark\Core\Exception;
use Lark\Annotation\Message;
use Throwable;

class InterfaceException extends Exception
{
    /**
     * @Message("参数 [%s] 错误啦")
     */
    public const PARAMS_EXCEPTION = 40001;

    /**
     * @Message("其他 [%s] 错误啦")
     */
    public const OTHER_EXCEPTION = 40002;

    /**
     * InterfaceException constructor.
     * @param int $code
     * @param array $data
     * @param Throwable|null $previous
     */
    public function __construct(int $code = 0, array $data=[], Throwable $previous = null)
    {
        /** @var Throwable $previous */
        parent::__construct($code, $data, $previous);
    }
}

throw new InterfaceException(InterfaceException::PARAMS_EXCEPTION, ['name']);


namespace App\Entitys;


use Lark\Annotation\Model\Column;
use Lark\Annotation\Model\Table;
use Lark\Database\Entity;

/**
 * @Table(name="users")         #对应表名称
 */
class UserEntity extends Entity
{
    /**
     * 主键ID
     *
     * @Column(name="uid",pk=true)  #主键
     * @var int
     */
    private $uid;

    /**
     * 用户ID
     *
     * @Column(name="name")         #字段name
     * @var string
     */
    private $name;

    /**
     *
     * @Column(name="age")
     * @var int
     */
    private $age;

    /**
     *
     * @Column(name="created")
     * @var int
     */
    private $created;

    /**
     *
     * @Column(name="enable")
     * @var int
     */
    private $enable;

    /**
     * @return int
     */
    public function getUid(): int
    {
        return $this->uid;
    }

    /**
     * @param int $uid
     */
    public function setUid(int $uid): void
    {
        $this->uid = $uid;
    }

    /**
     * @return string
     */
    public function getName(): string
    {
        return $this->name;
    }

    /**
     * @param string $name
     */
    public function setName(string $name): void
    {
        $this->name = $name;
    }

    /**
     * @return int
     */
    public function getAge(): int
    {
        return $this->age;
    }

    /**
     * @param int $age
     */
    public function setAge(int $age): void
    {
        $this->age = $age;
    }

    /**
     * @return int
     */
    public function getCreated(): int
    {
        return $this->created;
    }

    /**
     * @param int $created
     */
    public function setCreated(int $created): void
    {
        $this->created = $created;
    }

    /**
     * @return int
     */
    public function getEnable(): int
    {
        return $this->enable;
    }

    /**
     * @param int $enable
     */
    public function setEnable(int $enable): void
    {
        $this->enable = $enable;
    }
}

#查找单条数据
UserEntity::find($id);

#添加数据
$user = new UserEntity();
$user->setName($name);
$user->setEnable($enable);
$user->setAge($age);
$user->setCreated(time());

$user->save();

# host.php

/**
 * 系统需要监听的事件在此配置
 */
return [
    "host" => "177.16.345.1",
    "port" => 3309
];

//然后我们可以在代码中取得对于配置数据
$host_info = Config::get(null, 'host');
$port = Config::get('port', 'host')