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);
}
}