


On PHP interface version control [compatible with multi-terminal interfaces]
推荐:《PHP视频教程》
在对接第三方接口的时候,总是会看到接口后缀会带着v1,v2这样的标识,我们知道这些都是接口版本的概念,那么如果我方需要提供对外的接口,或者对接web端和APP端的时候,希望公用同一个接口,但是接口所渲染的数据表现形式不太一致,以及接口授权也不太一致的情况下,如何做到使用不同版本,且不同版本直接互不影响且同时共存呢?
首先笔者在考虑到接口设计时,有几大模块:
控制器层(controller):笔者将其定义为入口层(相当于java的dao层)
服务层(services):逻辑服务层,控制器入口层通过版本号标识转接到不同的服务层,具体的代码逻辑实现都在此处编写
行为层(behavior):也可理解为事件层,服务中间件,行为钩子都将在此处控制,入口权限过滤校验,对接第三方服务扩展通过行为钩子抽出,不让其加大服务层的代码臃肿
模型层(model):该层根据实际业务和开发习惯而定,可要可不要
校验层(validate):笔者认为很有必要,所有独立拉出一个目录来做相关校验,不管是独立校验,校验引擎,还是框架自带校验都在该目录定义,方便维护和扩展
公共层(common):系统公共代码,比如附件上传,下载等
配置层(config):内部配置,根据需求自定义是否需要
语言包(lang):根据需求而定
复用层(tarits):根据实际需求而定
任务层(job):根据实际需求而定
目录层级如图所示:
那么在入口层如何转接到服务层呢?因为在这过程我们会将接口中的版本号转接到不同的版本服务层。
首先在控制器入口层写一个基类控制器,后续所有的控制器都将会继承该类,在构造函数中调取行为类中的解析服务层代码,将服务层类初始化给基类变量!
public $service = null; /** * 构造函数处理头部请求 * * @return void */ public function __construct($type = 0, Request $request) { // 登录跳过 if (!$type) { // 注册行为监听 Hook::add('app_init', [ // 校验请求接口的身份(身份验证) 'app\\saas\\behavior\\AuthToken' ]); Hook::listen('app_init', []); } // 立即执行初始化控制器服务应用 $this->service = Hook::exec('app\\saas\\behavior\\InitializtionService', ['tag' => $type, 'request' => $request]); }
服务InitializtionService解析路由,判断,将服务层实例化
public function run($params) { // 兼容控制器分层,优化控制器目录结构 $controller = request()->controller(); $controllerArray = explode('.', $controller); $controllerLength = count($controllerArray); $appendControllerName = ''; if ($controllerLength == 1) { $appendControllerName = $controllerArray[0]; } else { for ($i = 0; $i < $controllerLength - 1; $i++) { $appendControllerName .= strtolower($controllerArray[$i]) . '\\'; } $appendControllerName .= ucfirst($controllerArray[($controllerLength - 1)]); } // $controller = '\\app\\saas\\controller\\' . request()->controller(); $controller = '\\app\\saas\\controller\\' . $appendControllerName; $verion = request()->param('version'); $init_service = function () use ($controller, $verion, $params) { // dump($controller); // $controller = '\app\saas\controller\test\Test'; $reflection = new \ReflectionClass($controller); if (property_exists($controller, 'versions') && isset($reflection->getStaticProperties()['versions'][$verion]) ) { // 默认规则返回,在前在后不允许返回其他信息 $service = $reflection->getStaticProperties()['versions'][$verion]; // 判断控制器服务文件是否存在 return class_exists($service) ? new $service($params['tag'], $params['request']) : Merror::getInstance()->jsonApi(40006); } else { Merror::getInstance()->jsonApi(40001); } }; return is_null($verion) ? Merror::getInstance()->jsonApi(40002) : $init_service(); }
这样在控制器中文件定义如下调用服务层逻辑代码,而不用关心是属于哪个服务层类,服务层代码只和版本有关
class Sysorder extends Saas { /** * 版本服务调度属性--必须默认一个且是v1 * * @var array */ protected static $versions = [ 'v1' => \app\saas\services\syscenter\Sysorder::class, ]; /** * 获取信息集权限目录 * * @method POST|GET * @name getSubMenuListCate */ public function getSubMenuListCate() { return json($this->service->getSubMenuListCate()); } /** * 获取列表 * * @method POST|GET * @name getSysOrderList */ public function getSysOrderList() { return json($this->service->getSysOrderList()); }
结语:此设计抛砖引玉,具体实现看各位phper大显神通了!
api多版本接口设计模式,可以参考(基于ThinkPhp5.1实现,框架不同,设计理念一致):www.kancloud.cn/lijianlin/ethantp5...
最后推广一下笔者自研的一套基于laravel设计的工作流流程引擎(https://learnku.com/laravel/t/48967),欢迎研究自研!
注:我这个设计主要是为了多版本接口开发的一种设计而已,每个人都有自己的开发习惯,不予强制,只是以便代码的维护和阅读!仅此建议而已
The above is the detailed content of On PHP interface version control [compatible with multi-terminal interfaces]. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Laravel's configuration cache improves performance by merging all configuration files into a single cache file. Enabling configuration cache in a production environment can reduce I/O operations and file parsing on each request, thereby speeding up configuration loading; 1. It should be enabled when the application is deployed, the configuration is stable and no frequent changes are required; 2. After enabling, modify the configuration, you need to re-run phpartisanconfig:cache to take effect; 3. Avoid using dynamic logic or closures that depend on runtime conditions in the configuration file; 4. When troubleshooting problems, you should first clear the cache, check the .env variables and re-cache.

UseMockeryforcustomdependenciesbysettingexpectationswithshouldReceive().2.UseLaravel’sfake()methodforfacadeslikeMail,Queue,andHttptopreventrealinteractions.3.Replacecontainer-boundserviceswith$this->mock()forcleanersyntax.4.UseHttp::fake()withURLp

Create referrals table to record recommendation relationships, including referrals, referrals, recommendation codes and usage time; 2. Define belongsToMany and hasMany relationships in the User model to manage recommendation data; 3. Generate a unique recommendation code when registering (can be implemented through model events); 4. Capture the recommendation code by querying parameters during registration, establish a recommendation relationship after verification and prevent self-recommendation; 5. Trigger the reward mechanism when recommended users complete the specified behavior (subscription order); 6. Generate shareable recommendation links, and use Laravel signature URLs to enhance security; 7. Display recommendation statistics on the dashboard, such as the total number of recommendations and converted numbers; it is necessary to ensure database constraints, sessions or cookies are persisted,

CheckPHP>=8.1,Composer,andwebserver;2.Cloneorcreateprojectandruncomposerinstall;3.Copy.env.exampleto.envandrunphpartisankey:generate;4.Setdatabasecredentialsin.envandrunphpartisanmigrate--seed;5.Startserverwithphpartisanserve;6.Optionallyrunnpmins

Create a seeder file: Use phpartisanmake:seederUserSeeder to generate the seeder class, and insert data through the model factory or database query in the run method; 2. Call other seeder in DatabaseSeeder: register UserSeeder, PostSeeder, etc. in order through $this->call() to ensure the dependency is correct; 3. Run seeder: execute phpartisandb:seed to run all registered seeders, or use phpartisanmigrate:fresh--seed to reset and refill the data; 4

Create a new Laravel project and start the service; 2. Generate the model, migration and controller and run the migration; 3. Define the RESTful route in routes/api.php; 4. Implement the addition, deletion, modification and query method in PostController and return the JSON response; 5. Use Postman or curl to test the API function; 6. Optionally add API authentication through Sanctum; finally obtain a clear structure, complete and extensible LaravelRESTAPI, suitable for practical applications.

Chooseafeatureflagstrategysuchasconfig-based,database-driven,orthird-partytoolslikeFlagsmith.2.Setupadatabase-drivensystembycreatingamigrationforafeature_flagstablewithname,enabled,andrulesfields,thenrunthemigration.3.CreateaFeatureFlagmodelwithfilla

The Repository pattern is a design pattern used to decouple business logic from data access logic. 1. It defines data access methods through interfaces (Contract); 2. The specific operations are implemented by the Repository class; 3. The controller uses the interface through dependency injection, and does not directly contact the data source; 4. Advantages include neat code, strong testability, easy maintenance and team collaboration; 5. Applicable to medium and large projects, small projects can use the model directly.
