如何访问包方法?

How to access a packages methods?

我正在开发一个 laravel 包,在包内我有一个处理数据的存储库。

当用户安装包时,我怎样才能让他们在他们的应用程序中与存储库交互?

我是否应该设置一个门面以便他们可以执行以下操作:

SuperPackage::getSomeData();

或者我应该使用不同的方式吗?

文档状态:

When building a third-party package that interacts with Laravel, it's better to inject Laravel contracts instead of using facades. Since packages are built outside of Laravel itself, you will not have access to Laravel's facade testing helpers.

我想这只是包的内部结构,在外部调用包,外观还可以吗?

由于无论如何您都非常需要编写一个服务提供程序来将您的包集成到用户的应用程序中,因此我认为您应该使用契约通过依赖注入使您的包可用。我不认为为了方便起见而提供一个门面也没什么坏处,因为实际上它只是一个额外的文件,它引用了您的服务提供商中的某些内容。

您的合同:

namespace Your\Package;

public interface YourPackageContract
{
    public function availableMethod();
}

您的实施:

namespace Your\Package;

class YourPackage implements YourContract
{
    public function availableMethod()
    {
        //  Implement your method
    }
}

您的服务提供商:

namespace Your\Package;

use Illuminate\Support\ServiceProvider;

class YourPackageServiceProvider extends ServiceProvider
{
    public function register()
    {
        // Tell Laravel that when an instance of YourPackageContract is requested, an instance of YourPackage should be returned
        $this->app->singleton('Your\Package\YourPackageContract', function($app) {
            return new YourPackage();
        });
    }

    public function provides()
    {
        return ['Your\Package\YourPackageContract'];
    }
}

你的门面:

namespace Your\Package\Facades;

use Illuminate\Support\Facades\Facade;

class YourPackage extends Facade
{
    public function getFacadeAccessor()
    {
        return 'Your\Package\YourPackageContract';
    }
}

在控制器中的用法:

class SomeController
{
    public function index(YourPackageContract $yourPackage)
    {
        // $yourPackage should now be an instance of YourPackage
        $yourPackage->availableMethod();

        // You can also use the Facade which refers to the same instance
        YourPackage::availableMethod();
    }
}

如果您想创建多种访问您的 class 的方法,您总是可以在您的服务提供商中使用 ->alias() 方法,使用更易读的名称等

注:我这里直接写的,还没来得及测试。