预信息:Laravel 5是我使用的第一个框架,除了我们多年来创建的自定义框架之外。我仍然围绕着这些概念,但它主要是在那里。我有页面调用,授权检查,表单提交和数据库查询都可以正常工作。
问题:过去我会创建一个新课程" Access"我会在任何需要的地方调用所需的功能:
$access = Access::getAccessByAccount($accountID);
我希望以某种方式在laravel中做同样的事情并且能够在控制器内调用这个公共函数。我只是不知道如何调用它以及在哪里实际存储函数。
以下是我想要致电的功能示例:
public function getAccessByAccount($accountID){
//Grab all access rights set to given account ID
$accessList = DB::table('element_access')
->join('element', 'element.id', '=', 'element_access.element_id')
->select('element.name as element', 'element_access.permission as permission')
->where('element_access.account_id', $accountID)
->get();
//Return $access[element] = permission list or false if no access rights are assigned to account ID
if(is_array($accessList)){
$access = array();
foreach($accessList as $item){
$access[$item->element] = $item->permission;
}
return $access;
}else{
return false;
}
}
以下是我想以某种方式在控制器中调用它的方式:
<?php namespace App\Http\Controllers\Portal\Admin;
use App\Http\Controllers\Controller;
class AdminController extends Controller {
public function showAdminDashboard(){
$access = Access::getAccessByAccount(Auth::id());
if($access['admin-dashboard'] == 'r'){
return view('portal.admin.dashboard');
}
}
}
编辑:
这是我在检查过的解决方案的帮助下提出的解决方案。
创建新文件:app \ Library \ Access.php
<?php namespace App\Library;
use DB;
class Access{
public function getElementAccessByAccount($accountID){
//Grab all access rights set to given account ID
return DB::table('element_access')
->join('element', 'element.id', '=', 'element_access.element_id')
->select('element.name as element', 'element_access.permission as permission')
->where('element_access.account_id', $accountID)
->get();
}
}
调用该函数:
$access = new \App\Library\Access;
$accessList = $access->getElementAccessByAccount(Auth::id());
答案 0 :(得分:0)
如果我愿意,我会将所有类别的自定义功能存储到app/services
目录。
访问类
<?php namespace App\Services;
class Access
{
public static function getAccessByAccount($accountID) {
//Grab all access rights set to given account ID
$accessList = \DB::table('element_access')
->join('element', 'element.id', '=', 'element_access.element_id')
->select('element.name as element', 'element_access.permission as permission')
->where('element_access.account_id', $accountID)
->get();
//Return $access[element] = permission list or false if no access rights are assigned to account ID
if (is_array($accessList)) {
$access = array();
foreach($accessList as $item){
$access[$item['element']] = $item['permission'];
}
return $access;
} else{
return false;
}
}
}
<强>控制器强>
<?php namespace App\Http\Controllers\Portal\Admin;
use App\Http\Controllers\Controller;
class AdminController extends Controller
{
public function showAdminDashboard() {
$access = \App\Services\Access::getAccessByAccount(\Auth::id());
if($access['admin-dashboard'] == 'r') {
return view('portal.admin.dashboard');
}
}
}