I love Laravel facade. With Laravel facade the code be more beautiful and readable than traditional approach. But, what if you don’t use Laravel? How to use the “facade”?

For example, I want to use Laravel “File” facade inside of my application.

First, I need to install illuminate/filesystem via composer.

composer require illuminate/filesystem

Then, just load the composer autoloader and create a new class like this

<?php

require 'vendor/autoload.php';

use Illuminate\Filesystem\Filesystem;

class File
{
    public static function __callStatic($name, $args)
    {
        $self = new Filesystem;

        return $self->{$name}(...$args);
    }
}

Finally, we can use File:: like in Laravel.

File::allFiles('./');

File::get('somefile.txt');

UPDATE 23 Aug 2016 – illuminate/config

For example I have folder structure like this

\ - assets/
  - config/
     \ - database.php
       - site.php
       - mail.php

Inside of database.php, site.php, mail.php just simple array. Example of database.php

<?php

return [
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'test',
];

Here’s the main file to load all configurations.

<?php

require 'vendor/autoload.php';

use Illuminate\Config\Repository;

class Config
{
    protected static $instance;

    public static function __callStatic($method, $args)
    {
        if (! static::$instance) {
            static::$instance = new Repository(
                (new self)->loadConfig('config')
            );
        }

        return static::$instance->{$method}(...$args);
    }

    protected function loadConfig($configPath)
    {
        $items = [];

        foreach(scandir($configPath) as $file) {
            if (substr($file, -4) === '.php') {
                $filename = str_replace('.php', '', $file);
                $items[$filename] = require $configPath . '/' . $file;
            }
        }

        return $items;
    }
}

To get the configuration, just use Config::

Config::get('database.username');             // root
Config::set('database.username', 'newuser');  // Set new value
Config::get('database.username');             // newuser

Config::all();  // All configs
Iklan

Tinggalkan Balasan

Please log in using one of these methods to post your comment:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s