Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working directly with libraries instead of bundles in Symfony2

Tags:

php

symfony

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.

like image 650
Adib Aroui Avatar asked Nov 16 '25 17:11

Adib Aroui


1 Answers

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:

  • Composer schema, "autoload" key
  • What is the difference between PSR-0 and PSR-4?
  • PSR-0
  • PSR-4
like image 150
felipsmartins Avatar answered Nov 18 '25 07:11

felipsmartins