Behzad Azizan
Behzad Azizan

Reputation: 33

how to access to laravel global Classes in packages

I am developing a Laravel package . In the packeges I need to File::delete for delete files, but The following error message is displayed :

Class 'Chee\Image\File' not found

Can you help me?

Upvotes: 0

Views: 865

Answers (3)

coffe4u
coffe4u

Reputation: 538

You should be able to just use:

\File

Namespaces are relative to the namespace you declare for the class you are writing. Adding a "\" in front of a call to a class is saying that we want to look for this class in the root namespace which is just "\". The Laravel File class can be accessed this way because it is an alias that has an declared in the root namespace.

Upvotes: 1

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87719

You have to declare it in the top of your class:

namespace Chee\Image;

use File;

class Whatever()
{

}

Instead of using the File Facade, you can also get it directly from the Laravel IoC container:

$app = app();

$app['files']->delete($path)

In a service provider, you can inject it as a dependency your package class:

class Provider extends ServiceProvider {

    public function register()
    {
        $this->app['myclass'] = $this->app->share(function($app)
        {
            return new MyClass($app['files']);
        });
    }

}

And receive it in your class:

class MyClass {

    private $fileSystem;

    public function __construcy($fileSystem)
    {
        $this->fileSystem = $fileSystem;
    }

    public function doWhatever($file)
    {
        $this->fileSystem->delete($file)
    } 

}  

Upvotes: 1

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

Assuming you have file something like that:

<?php

namespace Chee\Image;

class YourClass 
{
   public function method() {
     File::delete('path');
   }
}

you should add use directive:

<?php

namespace Chee\Image;

use Illuminate\Support\Facades\File;

class YourClass 
{
   public function method() {
     File::delete('path');
   }
}

Otherwise if you don't use PHP is looking for File class in your current namespace so it is looking for Chee\Image\File. You could look at How to use objects from other namespaces and how to import namespaces in PHP if you want

Upvotes: 0

Related Questions