Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine
This tutorial has a new version, check it out!

Bundles

Video not working?

It looks like your browser may not support the H264 codec. If you're using Linux, try a different browser or try installing the gstreamer0.10-ffmpeg gstreamer0.10-plugins-good packages.

Thanks! This saves us from needing to use Flash or encode videos in multiple formats. And that let's us get back to making more videos :). But as always, please feel free to message us.

Woh! You're back! Hey friend! Ok, I'm glad you're here: this is a big episode for us. We're about to learn some of the most critical concepts that will really help you to master Symfony... and of course, impress all your friends.

Like always, you should totally code along with me. Download the code from the course page and move into the start directory. I already have that ready, so let's start the built-in web server. Open a new terminal tab and run the ./bin/console server:run command:

./bin/console server:run

Ding! Now dust off your browser and try to load http://localhost:8000/genus/octopus, which is the page we made in the last tutorial. Awesome!

The 2 Parts of Symfony

After episode 1, we already know a lot. We know that Symfony is pretty simple: create a route, create a controller function, make sure that function returns a Response object and then go eat a sandwich. So, Route -> Controller -> Response -> Sandwich. And suddenly, you know half of Symfony... and you're not hungry anymore.

The second half of Symfony is a all about the huge number of optional useful objects that can help you get your work done. For example, there's a logger object, a mailer object, and a templating object that... uh... renders templates. In fact, the $this->render() shortcut we've been using in the controller is just a shortcut to go out to the templating object and call a method on it:

... lines 1 - 11
namespace Symfony\Bundle\FrameworkBundle\Controller;
... lines 13 - 38
abstract class Controller implements ContainerAwareInterface
{
... lines 41 - 185
protected function render($view, array $parameters = array(), Response $response = null)
{
if ($this->container->has('templating')) {
return $this->container->get('templating')->renderResponse($view, $parameters, $response);
}
... lines 191 - 202
}
... lines 204 - 396
}

All of these useful objects - or services - are put into one big beautiful object called the container. If I give you the container, then you're incredibly dangerous: you can fetch any object you want and do anything.

How do we know what handy services are inside of the container? Just use the debug:container command:

./bin/console debug:container

You can even search for services - like log:

./bin/console debug:container log

But Where do Services Come From?

But where do these come from? What magical, mystical creatures are providing us with all of these free tools? The answer is: the bundle fairies.

In your IDE, open up app/AppKernel.php:

... lines 1 - 5
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
... lines 18 - 20
new AppBundle\AppBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'), true)) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
... lines 33 - 52
}

The kernel is the heart of your Symfony application... but it really doesn't do much. Its main job is to initialize all the bundles we need. A bundle is basically just a Symfony plugin, and its main job is to add services to your container.

Remember that giant list from a minute ago? Yep, every single service in that list is provided to us from one of these bundles.

But at its simplest: a bundle is basically just a directory full of PHP classes, configuration and other goodies. And hey, we have our own: AppBundle:

... lines 1 - 5
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
... lines 11 - 20
new AppBundle\AppBundle(),
);
... lines 23 - 31
}
... lines 33 - 52
}

Install a Bundle: Get more Services

I have challenge for us: I want to render some of this octopus information through a markdown parser. So the question is, does Symfony already have a markdown parsing service?

I don't know! Let's find out via debug:container:

./bin/console debug:container markdown

Hmm, nothing: there's no built-in tool to help us.

Symfony community to the rescue! If you're missing a tool, there might be a Symfony bundle that provides it. In this case, there is: it's called KnpMarkdownBundle.

Copy its composer require line. You don't need to include the version constraint: Composer will figure that out for us. Run that in your terminal:

composer require knplabs/knp-markdown-bundle

Let's keep busy while that's working. To enable the bundle, grab the new statement from the docs and paste that into AppKernel: the order of these doesn't matter:

... lines 1 - 5
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
... lines 11 - 18
new Knp\Bundle\MarkdownBundle\KnpMarkdownBundle(),
... lines 20 - 21
);
... lines 23 - 31
}
... lines 33 - 52
}

That's it! Just wait for Composer to finish its job... and maybe send a nice tweet to Jordi - he's the creator and maintainer of Composer. There we go!

Ok, before we do anything else, let's run an experiment. Try running debug:container again with a search for markdown.

./bin/console debug:container markdown

Boom! Suddenly, there are two services matching. These are coming from the bundle we just installed. The one we're really interested in is markdown.parser.

Leave a comment!

68
Login or Register to join the conversation

Could anybody help me with the download link? I code along but since I could not download the page it takes me a little eternity to follow up. Thanks in advance.

Reply

Can´t you download the source code? There is a button at the right upper corner of this page named "Download" just click it and choose the option "Course code", or just go to: https://knpuniversity.com/s...

Cheers!

Reply
Default user avatar
Default user avatar Cự Nhân Nguyễn Liêm | posted 4 years ago

Hello, I tried to install the knp markdown bundle by using

composer require knplabs/knp-markdown-bundle

It located that the the version gonna be used is:

Using version ^1.4 for knplabs/knp-markdown-bundle

However, after that no other message was pop up regarding knp bundle but others packet having some kind of "satisfiable by" respond, none of which related to knp bundle.

I tried to fix the problem but it seems like I hit a dead end, nothing regarding knp bundle came out of my console, but when i tried to use

new Knp\Bundle\MarkdownBundle\KnpMarkdownBundle()

in my AppKernel but it always return a fatal error:

PHP Fatal error: Class 'Knp\Bundle\MarkdownBundle\KnpMarkdownBundle' not found in /home/cyberliem/encryAssign/myEncryptor/app/AppKernel.php on line 19

Is this the error at my end, or the KNP markdown bundle isn't there anymore?

Reply

Hi there!

Hmm, yes - you got a Composer dependency problem: there is *some* version incompatibility either with KnpMarkdownBundle or some existing packages in your project. So, the library was *not* downloaded. There could be many reasons for this (but it is weird). If you post the output from Composer (after running composer require) we should be able to find the problem :).

Cheers!

Reply
Default user avatar
Default user avatar Thorsten Ryba | weaverryan | posted 4 years ago

I do have the same problem here. Any solutions, yet ?

Reply

Hey Thorsten!

Can you post the output of your terminal after you run composer require knplabs/knp-markdown-bundle? As far as I know, you are the only ones that have had this issue, so it must be some small weird thing with your system (and something I'm sure we can fix!). The problem is somewhere in that terminal output, but sometimes it can be hard to dig through it and find the issue.

Cheers!

Reply
Default user avatar
Default user avatar Thorsten Ryba | weaverryan | posted 4 years ago

I can't post it anymore, but it was a dependecy error. As I started my Symfony track from scratch, composer wasn't able to find a viable solution for the new dependecy. I simply downloaded the source code from the tutorial and this fixed the issue.

Reply

Glad you got it fixed either way! If anyone else has a dependency error in the future, I'd still love to see the output to figure out the problem - I'm curious! :)

Cheers!

Reply
Default user avatar
Default user avatar Marco La Cugurra | posted 4 years ago

Hey guys :) I can't manage to get the markdown bundle via composer, once I launch the command I get this response:

MacBook-Pro-di-Marco:aqua_note Marco$ composer require knplabs/knp-markdown-bundle

-bash: composer: command not found

what am I doing wrong ?

some minutes later I realized that I could edit the composer.json file and I added "knplabs/knp-markdown-bundle": "~1.3" and then updated with this command php composer.phar update. And now everything works :) thank you anyway ^^

Reply

Hey Marco!

Nice job finding the fix! In the future, you could have run "php composer.phar require ....". Basically, composer can be installed 2 different ways - either globally (so then you say composer require, or composer update) or just locally where you have a composer.phar file (then you say php composer.phar require, php composer.phar update). It can be a confusing thing - and you'll see both variants used in tutorials, because we're all split on how we install Composer :).

Cheers!

Reply
Default user avatar
Default user avatar Valdass87 | posted 4 years ago

Hello, I have some problems, aqua_note project web-server doesn't start:

PHP Warning: require(/start/app/../vendor/autolload.php): failed to open stream: No such file or directory in /start/app/autoload.php on line 11

Fatal error: require(): Failed opening required '/home/../KNPU/start/app/../vendor/autoload.php' (include_path='.:/usr/share/php:/usr/share/pear') in /home/../KNPU/start/app/autoload.php on line 11

Reply

Hi there!

Download composer and then (in the project directory - e.g. the "start" directory) run:


php composer.phar install

(or just composer install - depending on how you installed Composer). I forgot to mention this step in the tutorial - there are more instructions in the README in that directory. But if you have issues after this, just let me know here :).

Cheers!

1 Reply
Default user avatar

Hi! I've done everything you explain and got

Whoops, looks like something went wrong.
1/1ClassNotFoundException in app_dev.php line 27:Attempted to load class "AppKernel" from the global namespace.
Did you forget a "use" statement for e.g. "Symfony\Bundle\FrameworkBundle\Tests\Functional\app\AppKernel" or "Symfony\Bundle\SecurityBundle\Tests\Functional\app\AppKernel"?
in app_dev.php line 27

During the work with composer, I had to reinstall it cause it showed me the following error:
[Seld\JsonLint\ParsingException]
"./composer.json" does not contain valid JSON
Parse error on line 1:
^
Expected one of: 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

How can I solve my issue?

Reply

Hey Andjii,

Let's start with you composer.json first. This error means you have invalid JSON syntax. If you provide me you composer.json file - I could help you with it. You could post you composer.json content here, in comment, but better use GitHub Gist and just attach a link to your Gist in comment.

Cheers!

Reply
Default user avatar

Thank you! I've found out that my composer.json is absolutely clear.... Don't I don't know, why. Now I restored it and everything works fine=))

Reply
Default user avatar
Default user avatar Guvenc Acarkan | posted 4 years ago

how do you download the source code? I have been looking over the course page and all the site, but can't find it here or in the github account for the site.

Reply

Hey Guvenc,

If course is not free - you should be logged in on KnpUniversity and have an access to a course (have a paid subscription or a purchased course you want to download). Then you should see a "Download" button on each screencast page of course in the top right corner. Let us know if you still have a problem with it.

Cheers!

Reply
Default user avatar

The Source code is downloadable on the first Course not on this page !
The fuirst Symfony course is here : http://knpuniversity.com/sc...

Reply
Default user avatar

Hi,

Here is the output:

$ composer require knplabs/knp-markdown-bundle
Using version ^1.5 for knplabs/knp-markdown-bundle
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
- Removing symfony/polyfill-apcu (v1.2.0)
- Removing psr/cache (1.0.0)
- Removing twig/twig (v1.24.0)
- Installing twig/twig (v1.23.1)
/c/ProgramData/ComposerSetup/bin/composer: line 10: 5260 Segmentation fault php "${dir}/composer.phar" "$@"

Alternatively I run:

$ composer dump-autoload

$ composer update

Output:

Loading composer repositories with package information
Updating dependencies (including require-dev)
- Removing twig/twig (v1.24.0)
- Installing twig/twig (v1.24.1)
/c/ProgramData/ComposerSetup/bin/composer: line 10: 8376 Segmentation fault php "${dir}/composer.phar" "$@"

How can I fix this?

Reply

Ah, Segmentation fault!!!! That's never good. Seg-faults are when PHP dies for some crazy reason, and it's *usually* (especially in a high quality library like Composer) due to some PHP bug or idiosyncratic issue on your system. It's not your fault, and it's rare, but these things happen. I have 2 suggestions:

1) Update to the latest version of Composer, just in case other people are having this issue and they have found some workaround for it

2) Upgrade your version of PHP. You probably don't need to upgrade to a whole new version (like 5.5 to 5.6 or 5.6 to 7), just a "patch" version (e.g. 5.5.10 to 5.5.12).

By the way, what version of PHP are you running? And what operating system?

Reply
Default user avatar

It's Windows 8 and the newest PHP version 7.06 + newest composer. I have tried to play around with different PHP versions and it turned to be futile.

Reply

Ah, Windows sometimes not so friendly for PHP developers. :(

How did you install PHP on your OS? Do you use any local web server packs like XAMPP or something similar?

Reply
Default user avatar

Hi Ryan,

Thank you for your tutorial. I'm new to Symfony and your help is just AWSOME !

Do you have a link to some page showing how to install/add bundles when Composer is not on the dev env ?...
This is due to the Security Admin who didn't install Composer on the dev env.

Thank's a lot !

Abou.

Reply

Hey Abou,

It's easy enough! You need to download composer as a PHAR archive to the project directory and execute it with PHP, for example:


$ php composer.phar install

Check out the "Download Composer" section on https://getcomposer.org/dow... : it gives you the `composer.phar` file. Or just download it manually: check out the "Manual Download" section there. For example, you can download it using WGET or CURL utilities in your terminal:


$ wget https://getcomposer.org/composer.phar
$ php composer.phar install

Cheers!

Reply
Default user avatar

Thank you so much !

Abou

Reply

You're welcome, Abou! ;)

Reply
Default user avatar

Now I got a cache:clear issue, then the install of composer won't complete. A permission problem. I'll handle this...
Thank you anyway !

After using your method does the use of composer remain the same ? I mean should I use the command composer as described in this tutorial ?...

*Don't minde ! I figured it out... I have to use "composer.phar" instead of "composer" as command !
Thank you anyway !

Cheers,
Abou

Reply

Yo Abou,

Check the https://getcomposer.org/doc... to install Composer globally on your server, then you can use it the same way we do in our tutorials ;)

Cheers!

Reply
Default user avatar

Hey!
I tried to install this via composer but after I installed composer, I move on to the next steps and it says (can not open input file: composer-setup.php)

Then when I tried to install the markdown bundle, it says (-bash: composer: command not found).

Thanks for the help :)

Reply

Hey Brian!

If you want to run "composer install" you have to installed it globally first: https://getcomposer.org/doc...
And then, go to the root of your project (or where you have your composer.json file) and run again composer install

I hope this fix your problem :)
Cheers!

Reply
Default user avatar

Thank you! Worked :)
Now I get this (Please provide a version constraint for the knplabs/knp-markdown-bundle requirement)

Reply

Hey Brian!

Sorry for the late response, that's weird if you installed it via composer require, a quick fix is to remove that line from your composer.json and running "composer require knplabs/knp-markdown-bundle" without specifying a version.
Another fix would be specifying a constraint like "~1.1" or "1.2.*" (adjust numbers to the desired version)
You can read more about composer versions here: https://getcomposer.org/doc...

Have a nice day!

Reply
Default user avatar

Hey guys, i think i might have a problem,
i downloaded all of the files needed, i even downloaded successfully the Knp Markdown bundle. But i saw that, when in terminal i write
php bin/console debug:container markdown
And then select the parser module to inspect it
i shows me this:

// This service is an alias for the service markdown.parser.max

Information for Service "markdown.parser.max"
=============================================

---------------- ---------------------------------------------
Option Value
---------------- ---------------------------------------------
Service ID markdown.parser.max
Class Knp\Bundle\MarkdownBundle\Parser\Preset\Max
Tags markdown.parser (alias: max)
Public no
Synthetic no
Lazy no
Shared yes
Abstract no
Autowired no
Autoconfigured no
---------------- ---------------------------------------------

is there something wrong on having the public value set as "no"?

Thanks for everythig, this tutorials are awesome

Reply
MolloKhan Avatar MolloKhan | SFCASTS | Ian | posted 4 years ago | edited

Hey Ian

Not really, the public option is designed for determining whether or not you can fetch out that service from the container, in this case you can't, but that's the reason of the alias.

Cheers!

Reply
Mike P. Avatar
Mike P. Avatar Mike P. | posted 4 years ago

One question regarding performance, does it make sense to include Bundles like Markdownbundle in AppKernel.php *instead* of just inserting it into the controller it is being used, if they only get used very occasually?
My question is, doesn't the performance of SF suffer from a lot of bundles inside AppKernel.php?

Reply

Hey Mike P.

I'm not sure if you can *just* use it directly inside a Controller, Symfony needs to compile and configure the bundle, so everything can work correctly. I don't think there is a performance impact at run time, because Symfony caches a lot of things after doing the bootstrap process (A process that runs once and only when you clear the cache)

Cheers!

1 Reply
Mike P. Avatar

One real world example, I use the ramsey/uuid package which can be included into the app.kernel. But I only use this function one time at registration. So it seems to be the case that there isn't anything that justifies loading it at every request?!
Would be great of you could shed some light onto the situation :)

Reply
Default user avatar
Default user avatar heitoralthmann | posted 4 years ago

Guys, where are the exercise files or the "tutorials" folder? I just COULDN'T find it =/

Reply

I replied you in the other comment. Could you find it?

1 Reply
Default user avatar
Default user avatar heitoralthmann | MolloKhan | posted 4 years ago

Thank you, Diego! :)

Reply
Default user avatar

I am getting the following warning/error when trying to run the server from the start folder. Is anyone able to diagnose this for me?

PHP Warning: require(/Users/<user>/Downloads/symfony-fundamentals/start/app/../vendor/autoload.php): failed to open stream: No such file or directory in /Users/<user>/Downloads/symfony-fundamentals/start/app/autoload.php on line 11

Warning: require(/Users/<user>/Downloads/symfony-fundamentals/start/app/../vendor/autoload.php): failed to open stream: No such file or directory in /Users/<user>/Downloads/symfony-fundamentals/start/app/autoload.php on line 11
PHP Fatal error: require(): Failed opening required '/Users/<user>/Downloads/symfony-fundamentals/start/app/../vendor/autoload.php' (include_path='.:') in /Users/<user>/Downloads/symfony-fundamentals/start/app/autoload.php on line 11

Fatal error: require(): Failed opening required '/Users/<user>/Downloads/symfony-fundamentals/start/app/../vendor/autoload.php' (include_path='.:') in /Users/<user>/Downloads/symfony-fundamentals/start/app/autoload.php on line 11

Reply

Yo Ed!

I know this error! First, let's fix it. Then, we can discuss why this may have happened. Here is the fix:

A) Download Composer https://getcomposer.org/dow...

B) In your terminal, move into your project. Then use Composer to download your project's dependencies:

php composer.phar install

Some people also install composer as a global command. In that case, the command would simply be composer install

Why did this happen? The vendor/ directory in your project - which is where Symfony and all the other vendor libraries live - is empty! This directory should also contain a file that helps Symfony boot up - that's the vendor/autoload.php file error that you're getting.

Why is this directory empty? The vendor/ directory is ignored from git, and also/similarly not included in our file download. And that's no problem - if I were to clone a project that you created, the vendor/ directory *will* and *should* be empty. As a PHP dev, I know to run composer install to populate it.

This is also mentioned in the README.md file in the start/ directory of the code download. But, I wanted to give you a bit more background... just in case it was useful!

Cheers!

Reply
Default user avatar

Ah the old, you can't run this programme until you've completed the steps on the readme error..

Thanks a lot for both the direction and the background information.

Reply
Default user avatar
Default user avatar Javier Tomas | posted 4 years ago

Hi,

I have a problem, after install knplabs/knp-markdown-bundle, when i try to start the console i says to me:

PHP Fatal error: Class 'AppKernel' not found in /home/wfg/aqua_note/bin/console on line 27

Any idea?

Reply

Hi Javier!

Super weird! It's possible that when you installed KnpMarkdownBundle and updated your app/AppKernel.php file (which is part of that process), you accidentally changed something else in that file, which broke things. If things were working before, then check that file to make sure that everything looks right - e.g. that the <<php sign is still there (this happens more than you think) and that the class still is called AppKernel (you didn't accidentally hit an extra key on your keyboard, etc).

Let me know what you find out! If everything looks good, post your AppKernel.php file here (I assume you haven't modified the bin/console file, so no need to see that).

Cheers!

Reply
Default user avatar
Default user avatar Maksimov Alexander | posted 4 years ago

./bin/console debug:container markdown does not work on Windows. How it is on Windows?

Reply

Hey Alexander,

It's difficult to understand what's wrong because don't show the error you have, but I suppose you need to run Symfony console through php, try this:

$ php ./bin/console debug:container markdown

If you still have an issue, show us the error you have

Cheers!

Reply
Default user avatar
Default user avatar Maksimov Alexander | posted 4 years ago

It does not work... I have installed a composer to php/my_symfony folder. php/my_s/composer.phar require knplabs/knp-markdown-bundle. I have it and... nothing. new Knp\Bundle\MarkdownBundle\KnpMarkdownBundle(), is still red. Why?

Reply
Default user avatar

Write use Knp\Bundle\MarkdownBundle\MarkdownParserInterface; in AppKernel.php.
This worked for me.

Reply
Default user avatar
Default user avatar Maksimov Alexander | Maksimov Alexander | posted 4 years ago

'Knp\\Bundle\\MarkdownBundle\\' => array($vendorDir . '/knplabs/knp-markdown-bundle'), I have it but (1/1) ClassNotFoundException
Attempted to load class "KnpMarkdownBundle" from namespace "Knp\Bundle\MarkdownBundle".
Did you forget a "use" statement for another namespace?

Reply
Cat in space

"Houston: no signs of life"
Start the conversation!

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": ">=5.5.9",
        "symfony/symfony": "3.1.*", // v3.1.4
        "doctrine/orm": "^2.5", // v2.7.2
        "doctrine/doctrine-bundle": "^1.6", // 1.6.4
        "doctrine/doctrine-cache-bundle": "^1.2", // 1.3.0
        "symfony/swiftmailer-bundle": "^2.3", // v2.3.11
        "symfony/monolog-bundle": "^2.8", // 2.11.1
        "symfony/polyfill-apcu": "^1.0", // v1.2.0
        "sensio/distribution-bundle": "^5.0", // v5.0.22
        "sensio/framework-extra-bundle": "^3.0.2", // v3.0.16
        "incenteev/composer-parameter-handler": "^2.0", // v2.1.2
        "composer/package-versions-deprecated": "^1.11", // 1.11.99
        "knplabs/knp-markdown-bundle": "^1.4" // 1.4.2
    },
    "require-dev": {
        "sensio/generator-bundle": "^3.0", // v3.0.7
        "symfony/phpunit-bridge": "^3.0" // v3.1.3
    }
}