Composer used to make PHP development very easier but not anymore! Now it’s one of requirement for any PHP projects. Now I show you hot to use this awesome and how you fall in love with it!
What is Composer and Why?
Composer is a dependency manager, simply it downloads and autoload the libraries your project need, for example your project need a template engine, you can manually download a template engine and put it into one of your project’s folder, you have to consider it in your autoloader or include some its classes in the best situation that you know which classes the main class depends on! But after reading this article you can tell Composer what you need and everything will be provided and ready-to-use.
How does Composer work?
Composer download the library your project need and put it in the directory named “
vendor” in your project’s root, there will be a file named “
autoload.php” in this vendor directory too which you must include it you project autoloader wherever it is, Composer autoloader include the libraries in your codes (classes) when you need it, notice that Composer use PHP namespace feature.
How to install Composer?
If your Windows user like me, you may download Composer Installer for Windows otherwise you can find appropriate installer for your OS.
How to use Composer?
It’s easy! go to your project root and run this command if you installed Windows Installer:
composer require company_name/package_name
or this one for other kind of versions:
php composer.phar require company_name/package_name
After executing command above, the package will be downloaded and installed in vendor folder, Composer creates two files named
composer.lock, I mention these this article later.
Where can I find packages (libraries)?
so if you need this library you just use one of these commands:
composer require neatplex/phplogger
php composer.phar neatplex/phplogger
Notice you must inlclude the
autload.php which is placed in vendor folder in your main project autoloader.
Now for example you want use Config class in this library, you must act like this:
use Afraware\PHPBundle\Config\Config; $config = new Config(); $config->setConfigFile(__DIR__ . "/config/app.php"); echo $config->get("mysql_username");
If you are unfamiliar with PHP namespaces, read the official manual.
you can update packages with running one of following commands in your project root:
php composer.phar update
Composer uses the file
composer.json in your project root to recognize the libraries and its versions which you imported to your project.
More about Composer
I suggest you to see Composer official documentation too.