How to Install and Use the Sylius Components

If you’re starting a new project (or already have a project) that will use one or more components, the easiest way to integrate everything is with Composer. Composer is smart enough to download the component(s) that you need and take care of autoloading so that you can begin using the libraries immediately.

This article will take you through using Taxation, though this applies to using any component.

Using the Taxation Component

1. If you’re creating a new project, create a new empty directory for it.

mkdir project/
cd project/

2. Open a terminal and use Composer to grab the library.

Tip

Install Composer if you don’t have it already present on your system. Depending on how you install, you may end up with a composer.phar file in your directory. In that case, no worries! Just run php composer.phar require sylius/taxation.

composer require sylius/taxation

The name sylius/taxation is written at the top of the documentation for whatever component you want.

3. Write your code!

Once Composer has downloaded the component(s), all you need to do is include the vendor/autoload.php file that was generated by Composer. This file takes care of autoloading all of the libraries so that you can use them immediately. Open your favorite code editor and start coding:

<?php

// Sample script.php file.

require_once __DIR__.'/vendor/autoload.php';

use Sylius\Component\Taxation\Calculator\DefaultCalculator;
use Sylius\Component\Taxation\Model\TaxRate;

$calculator = new DefaultCalculator();

$taxRate = new TaxRate();
$taxRate->setAmount(0.23);

$taxAmount = $calculator->calculate(100, $taxRate);

echo $taxAmount; // Outputs "23".

You can open the “script.php” file in browser or run it via console:

php script.php

Using all of the Components

If you want to use all of the Sylius Components, then instead of adding them one by one, you can include the sylius/sylius package:

composer require sylius/sylius

Now what?

Check out What is a Resource?, which will give you basic understanding about how all Sylius components look and work like.

Enjoy!