匿名函数的使用

臭大佬 2019-11-20 14:02:29 1318
php  laravel 
简介 匿名函数牛逼

几行代码解决一坨一坨的代码问题,哈哈哈
修改前

 $api->get('white_api', 'WhiteApiController@index');
$api->post('white_api', 'WhiteApiController@store');
$api->patch('white_api/{whiteApi}', 'WhiteApiController@update');
$api->get('white_api/{id}', 'WhiteApiController@show');
$api->delete('white_api', 'WhiteApiController@destroy');

$api->get('white_list', 'WhiteListController@index');
$api->post('white_list', 'WhiteListController@store');
$api->patch('white_list/{WhiteList}', 'WhiteListController@update');
$api->get('white_list/{id}', 'WhiteListController@show');
$api->delete('white_list', 'WhiteListController@destroy');

//或有n个这种相同的东西

....

修改后

$fun = function ($url_name, $contr_name) use ($api) {
$controller = $contr_name . 'Controller';
$api->get($url_name, $controller . '@index');
$api->post($url_name, $controller . '@store');
$api->patch($url_name . '/{' . $contr_name . '}', $controller . '@update');
$api->get($url_name . '/{id}', $controller . '@show');
$api->delete($url_name, $controller . '@destroy');
};

//白名单接口操作
$fun('white_api','WhiteApi');
//IP白名单
$fun('white_list','WhiteList');