简体   繁体   English

Laravel 5-具有全局访问权限的自定义帮助程序类

[英]Laravel 5 - Custom helper class with global access

My custom helper class is this: 我的自定义帮助程序类是这样的:

Located in app/bootstrap/ACL.php 位于app / bootstrap / ACL.php中

class ACL {

    public function __construct(){
       //Get user from session
       //Get user permission array
    }

    public function isAllowed($key){
        return 'calling from ACL class';
    }

} 

Now, I need to access this ACL class inside all of the project controllers. 现在,我需要在所有项目控制器中访问此ACL类。 So I require_once 'ACL.php'; 所以我require_once 'ACL.php'; in my app.php file. 在我的app.php文件中。

Then inside my controller I can do the following: 然后,在我的控制器中,我可以执行以下操作:

class UserController extends Controller {

    public function editDetails() {

        $acl = new \ACL();
        echo $acl->isAllowed('edit-details');

        //below is the code to edit details

    }
}

This code works, but I feel there should be a Laravel 5 proper way to do this. 这段代码有效,但是我觉得应该有Laravel 5正确的方式来做到这一点。 I want to know: 我想知道:

1) Is this approach OK or is there a better way to achieve this? 1)这种方法是否可行,还是有更好的方法来实现?

2) Without doing $acl = new \\ACL(); 2)不执行$acl = new \\ACL(); in every controller, can I use a global variable? 在每个控制器中,我可以使用全局变量吗? Or something like this ACL::isAllowed('edit-details'); 或类似这样的ACL::isAllowed('edit-details');

3) How can I run $acl->isAllowed('edit-details') condition in Blade templates properly? 3)如何在刀片模板中正确运行$acl->isAllowed('edit-details')条件?

Thanks a lot! 非常感谢!

Why don't you simply add it to the classmaps? 您为什么不简单地将其添加到类映射?

"autoload": {
  "classmap": [
      "app/Classes"
  ]
}

You can then put your class into the "/classes" folder under app and just use it. 然后,您可以将您的课程放在app下的“ / classes”文件夹中,然后使用它。 Just run 赶紧跑

composer dump-autoload

and then you can use it like other classes in laravel. 然后您就可以像laravel中的其他类一样使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM