Symfony 3: first steps
Today I’ve bootstrap Symfony 3.2.1 and start working with simplest things.
I have to say: that’s my first steps in using Symfony and this article will be interesting also for beginners only.
Review of base entities
Controller
Default Controller with routing in annotation:
src/AppBundle/Controller/DefaultController.php
class DefaultController extends Controller
{
/**
* @Route("/", name="homepage")
*/
public function indexAction(Request $request)
{
#...
}
}
To check please go to: http://localhost/
. And see page.
Service
In my case I would like to create new bundle:
We should create folder: src/CommonBundle
, file:src/CommonBundle/CommonBundle.php
for init bundle and add row new \CommonBundle\CommonBundle()
to the file app/AppKernel.php
Then we should create folder src/CommonBundle/Services
and service file: src/CommonBundle/Services/Someservice.php
<?php
namespace CommonBundle\Services;
class Someservice
{
}
Now we have physical file, but we couldn’t use it in our project. To do it we have to add
services:
common.someservice:
class: CommonBundle\Services\Someservice
to the file app/config/services.yml
Done!
Command
To create new command you could create file:
src/AppBundle/Command/DataParseCommand.php
- App
here is variable
<?php
/**
* Created by PhpStorm.
* User: artemn
* Date: 02/01/2017
* Time: 23:21
*/
namespace AppBundle\Command;
use CommonBundle\Services;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
class DataParseCommand extends ContainerAwareCommand
{
private
/**
* @var InputInterface
*/
$_input,
/**
* @var OutputInterface
*/
$_output,
/**
* @var Services\Bank
*/
$_parser;
protected function configure()
{
$this
// the name of the command (the part after "bin/console")
->setName('app:parse-data')
// the short description shown while running "php bin/console list"
->setDescription('Some description.')
// the full command description shown when running the command with
// the "--help" option
->setHelp("This command allows you to parse transaction's file...");
$this
// configure an arguments
->addArgument('required_arg', InputArgument::REQUIRED, 'The filePath is required.');
}
/**
* Execution of command.
*
* Example: web@fin:[/var/www/service]: php bin/console app:parse-data /var/www/service/data/data.csv
*
* @param InputInterface $input
* @param OutputInterface $output
* @return null
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->_output->writeln(['============', 'Fair enough!', '============']);
$this->_output->writeln($input->getArgument('required_arg'));
$this->getContainer()->get('common.someservice'); # that's instance of service which was defined in previous step.
}
}