4

How can I use a library directly inside an existing Symfony2 project. I am, for instance, trying to add the faker library. I installed it via composer but I don't know how and where to put the code I need.

According to documentation:

// require the Faker autoloader
require_once '/path/to/Faker/src/autoload.php';
// alternatively, use another PSR-0 compliant autoloader (like the Symfony2 ClassLoader for instance)

What is a simple explanation of auto loader? How to use a library directly without a bundle? Is it a requirement for a library to have an autoload.php file so that it can be integrated inside a php project? Where to put the above code?

Any links explaining such notions for newbies? Thank you very much for your usual guidance.

Community
  • 1
  • 1
Adib Aroui
  • 4,981
  • 5
  • 42
  • 94
  • 1
    You can try reading the [spec](http://www.php-fig.org/psr/psr-0/), the [PHP Manual autoloading documentation](http://php.net/manual/en/language.oop5.autoload.php) and the [Symfony `ClassLoader` component docs](http://symfony.com/doc/current/components/class_loader/index.html). – Jared Farrish Aug 16 '15 at 01:42
  • @JaredFarrish, I did for the symfony link with no luck from first reading, I will redo. Thanks for the php-fig link and php manual. – Adib Aroui Aug 16 '15 at 01:44
  • 1
    Autoloading itself is similar to path loading, except that the namespace for the class depicts where the class should be loaded from by describing a path mapping to directory mapping. This is so that you don't have to use `require` or `include` with actual paths. Here's also the [PSR-4 autoload spec](http://www.php-fig.org/psr/psr-4/), which supercedes PSR-0. – Jared Farrish Aug 16 '15 at 01:47

1 Answers1

9

You do not need to config nothing. Faker library is PSR-4 (see composer.json, this line) compliant so just install it (through composer) and use the proper namespace. Symfony automatically loads PSR-4 / PSR-0 libraries/components. Like this:

<?php # src/AppBundle/Controller/DefaultController.php
namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Faker;

class DefaultController extends Controller
{   
    public function indexAction()
    {

        $faker = Faker\Factory::create();
        var_dump($faker); die;
        // ...
    }
}

Helpful links:

felipsmartins
  • 13,269
  • 4
  • 48
  • 56