Symfony 3 Notes
>> Symfony 3
- In symfony we can write powerful well design code wheather its for API or for traditional web app.
- Symfony is set of components which all we say php libraries, We can use symfony in non symfony projects by using one of its libraries.
- Finder - searches really deep into directories.
- Symfony framework - taken all these components together to things done faster.
- In symfony - All the work is done by the different services.
- Symfony is firstclass tool to buld the APIs.
Finder - Listing and filtering (date, filename, etc) files and directories.
Console - Awesome commad-line applications with coloration, input/output & other goodies.
Process - Execute external process, check their or errors, send signals, run asynchronously.
Routing - Create a front controller (e.g. index.php) and flexible URL structure in any app.
Project that love symfony components - Drupal, Laravel, Magento, phpBB.
Symfony is also framework - we don't have to worry about bunch of libraries together.
Silex - mini symfony framework.(less components). We can also use combination of symfony & Slilex as both uses same peaces.
>> Install symfony?
- Get symfony installer
- $ symfony new nameofproject //it generates set of files and folder that symfony uses e.g. app, bin, src, vendor
- symfony libraries will besides in vendor directory
- $ php bin/console server:run // to start built in php web server (we can use Nginx or Apache)
- $ git init
- $ git add .
- $ git commit -m 'initial commit'
- $ git push
>> Symfony 3 folder structure?
src - Holds all php files (classes)
--BundleName
---Controller
---Entity
---Form
---Repository
---Resources
---Services
app - holds configurations, templates
-- AppCache.php
-- AppKernel.php
-- autoload.php
-- Resources
-- config
--- routing.yml
--- parameters.yml.dist
--- config.yml
--- parameters.yml
--- services.yml
--- security.yml
--- routing_dev.yml
--- config_test.yml
--- config_prod.yml
--- config_dev.yml
web - Is a document root direcotry. used for assets, anything in web direcotry can be accessed by the public.
-- asset
-- bundles
-- images
var - storing cache, logs, sessions
-- cache
-- logs
-- sessions
vendor - third party libraries or symfony bundles
bin - symfony console for internal symfony server purpose.
node_modules - node js dependencies
>> Symfony execution steps?
route
controller
Response
Output
>> Controller - page in two steps
1. route : configuration that says what the url is, routes match/execute from top to bottom in controller
2. controller - a function that builds the page.
In symfony namespace must match the directory structure.
- To add route (@Route) in controller it need to include "Sansio\Bundle\FrameworkExtraBundle\Configuration\Route"
- return new Response('Response from controller action'); //Response class in from "Symfony\Component\HttpFoundation\Response"
- routing-wildcards - is used to pass the variable to controller function. e.g. @Route("/welcome/{wildCardName}"), here wildCardName will be refer as $wildCardName as a function parameter in controller.
- To debug symfony application we can use "php bin/console " function with options. e.g. php bin/console debug:router
>> Services -
- Service is just a useful object. Objects in symfony called as services. e.g. send email, log something. Each object has key like key: mailer, key: logger.
- we not need to instantiate service class manually.
- By using service service class can be an Autobot so that we can use it directly without instantiate it.
- We have direct access to container inside controller.
e.g. //Register your Service in the Container, app/config/services.yml
# services:
# service_name:
# class: AppBundle\Directory\ClassName
# arguments: ["@another_service_name", "plain_value", "%parameter_name%"]
services:
rescounter_pf_core.misc_func_service:
class: ResCounterBundle\Services\MiscFuncService
arguments: ["@service_container"]
>> List all the services in symfony?
"debug:container" will list all of default services in symfony
e.g.
$ php bin/console debug:container
>> Container -
- We have direct access to container inside controller.
- contains on method get() you need to pass only name of service.
e.g.
$templating = $this->container->get('templating');
or
$this->get('templating');
>> What are these Tags in services?
- Tags are the way to hook your services into different parts of the core system.
- When Symfony creates the twig service, it looks for all services in the container that are tagged with twig.extension. It then configures these as extensions on twig.
e.g. app/config/services.yml
services:
app.markdown_extension:
class: AppBundle\Twig\MarkdownExtension
tags:
- { name: twig.extension }
>> Autowiring in services?
- In services.yml, remove arguments and instead just say autowire: true
- Symfony reads the type-hints for each constructor argument And tries to automatically find the correct service to pass to you.
e.g.
services:
app.markdown_extension:
#arguments: ['@app.markdown_transformer']
autowire: true; // this will not work on symfony 3.3 and higher, instead it work/load arguments automatically
>> app/Resources/views -
Templating by-default besides in app/Resources/view/ directory.
e.g.
$html = $templating->render('genus/show.html.twig');
or
$this->render('genus/show.html.twig');
>> Twig -
- Tags - extends, for, if, set, do, spaceless, filter, macros
- Filters - abs, batch, date, escape, length, round, replace, slice,
- Functions - block, constant, dump, max, min, attribute
- Tests - defined, constant, empty, even, null, odd
- Operators - in, is, Math, Logic, Comparisons.
- has two syntaxes {{ }} is say something tag (print something) and {% %} is do something tags(is for conditional statements).
e.g.
{{ dump() }} print everthing in twig file which is assigned from controller.
>> Layouts in Twig -
layout can be use for templating twig.
e.g.
{% extends 'base.html.twig' %}
>> Assets -
- asset() function whenever we refer to static file we wrap the path in asset function. Symfony can prefix every static file with cdn with url host.
- path() - to generate/call route url in twig use path function.
>> Create API endpoints in symfony -
- Symfony controller was always returns response interms of html, json, csv, pdf etc.
- we can write function in controller with GET/POST method and return response with json encode/JsonResponse function.
e.g.
return new Response(json_encode($data));
OR
return new JsonResponse($data); // this calls json_encode automatically with sets application/json content type header on reponse automatically.
>> Install Bundles -
- All of useful objects/service are stored in one object called container.
- app/AppKernel.php - is heart of symfony. Its main job is to initialize all of bundles that we need.
- Bundles - is just a symfony plugin and its main job is to add services in to a container. Bundles (FrameworkBundle, TwigBundle, MonologBundle, KnpMarkdownBundle) put more services (logger, twig, translator, markdown.parser, router, form.factory) to project and services are tools.
>> Type of services in symfony default?
$ php bin/console debug:container // will list all of default services in symfony
>> Configure services or Control Center for Services -
we can import services.yml in "Config.yml" and we can add/configure service in app/config/services.yml file.
e.g.
services:
rescounter_pf_core.misc_func_service:
class: ResCounterBundle\Services\MiscFuncService
arguments: ["@service_container"]
>> Adding a Cache Service -
symfony bundle "DoctrineCacheBundle"
>> How to enable/add some bundle in symfony?
1. first add/check bundle in "composer.json" file
e.g.
"require": {
"doctrine/doctrine-cache-bundle": "^1.2",
}
2. The bundle lives in the vendor/ directory, but it isn't enabled. Do that in the AppKernel class in "app/AppKernel.php" with new DoctrineCacheBundle():
e.g.
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
new Doctrine\Bundle\DoctrineCacheBundle\DoctrineCacheBundle(),
);
}
}
3. Once you've enabled a bundle, there are usually two more steps: configure it, then use it using use statement on top of the class.
Configure the Bundle - $ ./bin/console config:dump-reference //The list has a new entry: doctrine_cache, $ ./bin/console config:dump-reference doctrine_cache
Configuring a Cache Service -
e.g.
app/config/config.yml add bellow code,
doctrine_cache:
providers:
my_markdown_cache:
type: file_system
>> where do routes come from? And can third party bundles give us more routes?
- when Symfony loads the route list, it only loads one routing file.
- In the dev environment, it loads routing_dev.yml and for dev enviorment there is additional routes from WebProfilerBundle and the TwigBundle.
- "debug:router " to list all the routes.
e.g.
$ ./bin/console debug:router
>> How can write route in route.yml file?
It means that we will have a controller in AppBundle called MainController with a method named homepageAction().
In app/config/routing.yml for controller specific route we can write like,
e.g.
homepage:
path: /
defaults:
_controller: AppBundle:Main:homepage
>> How to call view in another bundle?
return $this->render('ResCounterBundle:Pwa:hotel.html.twig', $parameters);
>> Doctrine -
- Is a ORM(Object Relational Mapper).
- Every table is has corresponding class.
- When you create "geniousTableName" table then doctrine gives you genious object.
- Every property in class has map to column in table.
- Mapping between table and php class is doctrines main goal.
- All of the tools in symfony are optional including doctrine.
- Symfony doesn't provide a component to work with the database, but it does provide tight integration with a third-party library called Doctrine.
- To install doctrine use $ composer require doctrine maker
>> Entity -
- For doctrine create/store file in Entity folder with some name we can put table name but its not compulsary. Entity is just a class that doctrine will map to database table. We can use drumroll anotations to map table columns (use Doctrine\ORM\Mapping as ORM;)
- fetches data from the database. Symfony don't care how you talk to database, Doctrine is not part of symfony you can use direct PDO connection, doctrine or do something else.
e.g. for genus table following is doctrine class in "AppBundle\Entity\Genus"
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
*@ORM\Entity
*@ORM\Table(name="genus")
*/
class Genus {
/**
*@ORM\Id
*@ORM\GeneratedValue(Strategy="AUTO")
*@ORM\Column(type="Integer")
*/
private $id;
/**
*@ORM\Column(type="String")
*/
private $name;
}
>> What are doctrine types in symfony?
Doctrine type are use to map table column data type.
- string
- integer
- float
- text
- datetime
e.g.
@ORM\Column(type="string") // here string is doctrine type
>> create table in symfony?
- $ ./bin/console doctrine:database:create // it will take database name from defined in config.yml file and create database
- $ ./bin/console doctrine:schema:update --dump-sql // to create table the table name will taken from Entity class, --dump-sql option is used to preview the query
- $ ./bin/console doctrine:schema:update --force // to create table in database
>> insert data in table using doctrine in controller?
e.g.
$genus = new Genus(); //doctrine class object for genus table
$genus->setName('Octopus'.rand(1, 100)); // sets the name column
$em = $this->getDoctrine()->getManager(); // used to make operation (save, update, delete) on tables
$em->persist($genus); // tells doctrine to save data to table
$em->flush(); // data will be save in table to this stage
>> How to run SQL queries like select * in symfony console?
$ ./bin/console doctrine:query:sql 'SELECT * FROM genus' // will display table records on console
>> Add some extra fields to table?
Add extra fields to entity class type and gettter and setter and on console fire update command "$ ./bin/console doctrine:schema:update --dump-sql" we can copy output query from this and run on command line for production server. Because fireing --force to update table fields will be dangerous and All the data from the old column would be gone! The point is: running doctrine:schema:update is just too dangerous on production.
>> Database Migrations
Our goal is to find a way to safely update our database schema both locally and on production. we can do that using doctrine:migrations.
- $ composer require doctrine/doctrine-migrations-bundle
- Add DoctrineMigrationsBundle class in AppKernel file
- $ ./bin/console doctrine:database:drop --force // drop database
- $ ./bin/console doctrine:database:create // create database
- $ ./bin/console doctrine:migrations:diff // instead of running doctrine:schema:update run this, This created a new file in app/DoctrineMigrations with up and down function
- $ ./bin/console doctrine:migrations:migrate // when you deploy, you'll also run this command, this command will only run the migration files that have not been executed before
- $ ./bin/console doctrine:migrations:diff // to create another migration e.g. for alter table command
- $ ./bin/console doctrine:migrations:migrate // open migration file and add alter command and fire this command after that
>> How to Making Columns nullable?
Doctrine configures all columns to be required in the database by default, If you do want a column to be "nullable", find the column in Entity file and add nullable=true.
e.g.
/**
* @ORM\Column(type="string", nullable=true)
*/
private $funFact;
>> List/find all the rows from table?
everything in Doctrine starts with the all-powerful entity manager, Pass this the class name - not the table name - that you want to query from: AppBundle\Entity\Genus. we can use methods like findAll() and findOneBy()
e.g.
$em = $this->getDoctrine()->getManager();
$genuses = $em->getRepository('AppBundle\Entity\Genus')->findAll();
OR
$genuses = $em->getRepository('AppBundle:Genus')->findAll(); // we can use The AppBundle:Genus Alias Internally, Doctrine converts this to AppBundle\Entity\Genus
dump($genuses);die;
$genus = $em->getRepository('AppBundle:Genus')->findOneBy(['name' => $genusName]); // find one record
>> Add dummy data using fixtures?
We can use "DoctrineFixturesBundle" bundle fixtures to add dummy data to tables.
e.g.
class LoadFixtures implements FixtureInterface
e.g. //src/AppBundle/DataFixtures/ORM/fixtures.yml
AppBundle\Entity\GenusNote:
genus.note_{1..100}:
username: <userName()>
userAvatarFilename: '50%? leanna.jpeg : ryan.jpeg'
note: <paragraph()>
createdAt: <dateTimeBetween('-6 months', 'now')>
$ ./bin/console doctrine:fixtures:load // load the fixtures
>> What is the Repository?
- In order to isolate, reuse and test these complex queries, it's a good practice to create a custom repository class for your entity.
- Methods containing your query logic can then be stored in repository class.
- A Repository is not a Model. The Entity represents your Model.
- The Repository interfaces to the database.
- Repository is only part that interacts with a DB. You use the default ones in most cases but do need one if you have some special queries. Business logic should not be here either. Entity a data structure. Almost never has a meaningful method that is not an accesor.
To map repository to entity add bellow in Entity file,
e.g.
// src/AppBundle/Entity/Product.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="AppBundle\Repository\ProductRepository")
*/
class Product {
//to create repository use bellow code
//src/AppBundle/Repository/ProductRepository.php
e.g.
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
class ProductRepository extends EntityRepository
{
public function findAllOrderedByName()
{
return $this->getEntityManager()
->createQuery(
'SELECT p FROM AppBundle:Product p ORDER BY p.name ASC'
)
->getResult();
OR
return $this->createQueryBuilder('genus')
->andWhere('genus.isPublished = :isPublished')
->setParameter('isPublished', true)
->orderBy('genus.speciesCount', 'DESC');
}
}
//in controller you can use repository directly
e.g.
class GenusController extends Controller
{
public function listAction()
{
$genuses = $em->getRepository('AppBundle:Genus')
->findAllOrderedByName();
}
>> The Relations?
Symfony supports bellow 2 types of relationships
- ManyToOne Association // each genus has many genus note but each note belongs to one genus
- ManyToMany Association // product has many tags but also each tag can have related to many products
//there are other relationships
OneToMany Association
OntToOne Association
Uni-directional Association
Bi-directional Association
e.g. to any many to relationship we need to add/refer one table id in to other table we can achive this by using bellow example, Doctrine will create a genus_id integer column for this property and a foreign key to genus
src/AppBundle/Entity/GenusNote.php
class GenusNote
{
/**
* @ORM\ManyToOne(targetEntity="Genus")
*/
private $genus;
e.g. Inverse relationship
//src/AppBundle/Entity/GenusNote.php
class GenusNote
{
/**
* @ORM\ManyToOne(targetEntity="Genus", inversedBy="notes")
* @ORM\JoinColumn(nullable=false) // or @ORM\OrderBy({"createdAt" = "DESC"})
*/
private $genus;
e.g.
src/AppBundle/Entity/GenusNote.php
class GenusNote
{
public function setGenus(Genus $genus)
{
$this->genus = $genus;
}
}
$ ./bin/console doctrine:migrations:diff //then generate migration
$ ./bin/console doctrine:migrations:migrate // apply/save
//apply the relationship in cotroller
//class GenusController extends Controller >> public function newAction()
$genus = new Genus();
$genus->setName('Octopus'.rand(1, 100));
$genus->setSubFamily('Octopodinae');
$genus->setSpeciesCount(rand(100, 99999));
$note = new GenusNote();
$note->setUsername('AquaWeaver');
$note->setUserAvatarFilename('ryan.jpeg');
$note->setNote('I counted 8 legs... as they wrapped around me');
$note->setCreatedAt(new \DateTime('-1 month'));
$note->setGenus($genus);
$em->persist($genus);
$em->persist($note);
$em->flush();
>> JoinColumn & Relations in Fixtures?
e.g.
src/AppBundle/Entity/GenusNote.php
class GenusNote
{
/**
* @ORM\ManyToOne(targetEntity="Genus")
* @ORM\JoinColumn(nullable=false)
*/
private $genus;
>> Join in doctrine?
e.g.
return $this->createQueryBuilder('genus')
->andWhere('genus.isPublished = :isPublished')
->setParameter('isPublished', true)
->leftJoin('genus.notes', 'genus_note')
->orderBy('genus_note.createdAt', 'DESC')
->getQuery()
->execute();
>> Dependency Injection?
- Means if class needs some object or some configuration we force that information to be pass in to that class Instead of reaching it outside of it using global or static variables.
- Service is any php class that performs an action.
>> Type hinting?
- We can use type hinting to variable pass in function or return type of function.
- Type hinting gives you the ability to define the type of values that can be passed for each argument of a function or method.
- Type hinting is optional, but when used it forces parameters to be a certain type or an error is thrown.
Benefits if Type hinting
- Type hinting is optional.
- If you pass something else then it will give much clear error message.
- Documents class even futher a developer now nows exactly what object should be called in while calling method.
- If you use IDE then it will gives an autocomplition.
e.g.
public function myfunction(SomeInterface $instance, SomeClassType $classRegular): SomeClassType {
}
e.g.
function (int $a, int $b) : int {
return $a + $b;
}
>> Create the Site Entity command line?
$ php app/console doctrine:generate:entity
>> get value from parameter.yml file in controller?
$baseHost = $this->container->getParameter('base_host');
>> How to (dynamically) remove a Form Field?
By removing the form field you want with the remove function
e.g.
$form = $this->createForm(new RemoveFormFieldType());
$form->remove('second'); // this will remove form field
return $this->render('QADayBundle:RemoveFormField:form.html.twig', array(
'form' => $form->createView()
));
By custom option passed on initialization.
e.g.
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('first', 'text');
if ($options['use_second']) {// condition to use custom option
$builder->add('second', 'text');
}
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'use_second' => true // this is custom option
));
}
>> RAD(Rapid Application Development) in symfony?
RadPHP was an IDE and rapid application development framework for the PHP programming language developed by Embarcadero Technologies.
using symfony we can achieved RAD bellow are some examples,
KnpRadBundle - A lot of love at Knp has been put into this little project, which takes the Symfony2 framework experience and makes it opinionated.
Laravel - Laravel4 is being built on top of Symfony2, This is another great example of taking our new solid core and making it quicker to develop things.
Silex - Silex is the micro-framework built on top of Symfony2, which lets you get an application going instantly. It’s not suitable for everything, and eventually you’ll wish you had more tools, but you’ll get started fast.
>> In Symfony what is best way (in your opinion) to organize structure for applications?
- you have a lot of flexibility on how to organize things,
- create a service-oriented architecture where all your business logic lives in services. This means having “skinny” controllers and a “fat” model. There will of course be edge-cases, but this is almost always the best way to organize things.
>> Strict controller to https and add browser cache?
e.g.
/**
* @Route(
* schemes = {"https"} // this will strict all urls in this controller to https
* )
* @Cache(
* maxage = "0",
* smaxage = "0",
* expires = "now",
* public = false
* )
*/
class HotelController extends BaseController {
}
>> Add rules or default values to url parameters
e.g.
class HotelController extends BaseController {
/**
* @Route(
* path = "/hotels/{location}/{humanId}/{hotelId}/{tabActive}{trailingSlash}",
* requirements = {"location": "[a-zA-Z0-9_-]+", "humanId": "([a-zA-Z0-9_-]+)?", "hotelId": "[a-z0-9]+","trailingSlash" : "[/]{0,1}","tabActive":"([a-zA-Z-]+)?"},
* defaults = {"humanId" : null, "trailingSlash" : null, "tabActive" : null},
* methods = {"GET"}
* )
*/
public function indexHotelsAction(Request $request, $location, $hotelId, $humanId, $tabActive) {
}
>> Add documentation of function parameter?
Adding documentaion to function parameter is not compulsary in symfony its optional,
e.g.
/**
* Get custom hotel details
*
* @param Request $request
* @param string $location
* @param string $hotelId
* @param string $humanId
* @return array
*/
private function getCustomHotelDetails(Request $request, $location = null, $hotelId = null, $humanId = null, $tabActive = null) {
}
>> Add condition to controller function to check if ajax method?
e.g.
/**
* @Route(
* path = "/ajax/hotel/nearby/",
* methods = {"POST"},
* condition = "request.isXmlHttpRequest()"
* )
*/
public function ajaxHotelsNearbyAction(Request $request) { }
>> What is class/bundle/namespace to include "Request" in symfony?
use Symfony\Component\HttpFoundation\Request;
e.g.
$request = new Request(); // or we can use type hint class from controller function directly
$request->query->get('check-in');
$request->cookies->get('rcv2_pikaday_start_format');
$request->getSession()->get('traced_hotels');
>> What is class/bundle/namespace to include "Session" in symfony?
use Symfony\Component\HttpFoundation\Session;
e.g.
$request->getSession()->set('traced_hotels', $traced_hotels);
$request->getSession()->get('traced_hotels');
//we can also use the session interface to store the session
use Symfony\Component\HttpFoundation\Session\SessionInterface;
e.g.
$session->set('foo', 'bar');
$foobar = $session->get('foobar')
>> What is class/bundle/namespace to include JsonResponse in symfony?
use Symfony\Component\HttpFoundation\JsonResponse;
e.g.
return new JsonResponse($dataArray);
>> What is class/bundle/namespace to include "Response" in symfony?
use Symfony\Component\HttpFoundation\Response;
e.g.
return new Response('<html><body>Lucky number: '.$number.'</body></html>');
>> What is class/bundle/namespace to include "Route" in symfony?
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
e.g.
/**
* @Route(
* path = "/hotel-ajax/{hotelId}/",
* methods = {"GET", "POST"}
* )
*/
public function ajaxAction(Request $request, $hotelId) {}
>> What is class/bundle/namespace to include "Cache" in symfony?
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
e.g.
/**
* @Route(
* schemes = {"https"}
* )
* @Cache(
* maxage = "0",
* smaxage = "0",
* expires = "now",
* public = false
* )
*/
class HotelController extends BaseController {}
>> What is the standard distribution?
Symfony distribution is made up of Symfony components, a selection of bundles, a directory structure, a default configuration, and an optional Web configuration system.
>> what is FOSRestBundle in symfony?
- The Symfony Security component provides a flexible security framework that allows you to load users from configuration, a database, or anywhere else you can imagine. The FOSUserBundle builds on top of this to make it quick and easy to store users in a database.
- FOSRestBundle (FriendsOfSymfony Bundle) provides various tools to rapidly develop RESTful API's & applications with Symfony like User registration and login management.
>> create form in symfony?
e.g.
// src/AppBundle/Form/GenusFormType.php
class GenusFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('speciesCount')
->add('funFact')
;
}
//Binding Forms to Objects: data_class
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => 'AppBundle\Entity\Genus'
]);
}
}
// src/AppBundle/Controller/Admin/GenusAdminController.php
use AppBundle\Form\GenusFormType;
class GenusAdminController extends Controller
{
/**
* @Route("/genus/new", name="admin_genus_new")
*/
public function newAction()
{
$form = $this->createForm(GenusFormType::class);
//validate and save data
if ($form->isSubmitted() && $form->isValid()) {
$genus = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($genus);
$em->flush();
$this->addFlash('success', 'Genus updated!');
return $this->redirectToRoute('homepage');
}
return $this->render('admin/genus/new.html.twig', [
'genusForm' => $form->createView()
]);
}
}
//in twig file we can write form admin/genus/new.html.twig
{{ form_start(genusForm) }}
{{ form_widget(genusForm) }}
<button type="submit" class="btn btn-primary">Save</button>
{{ form_end(genusForm) }}
OR
{{ form_start(genusForm) }}
{{ form_row(genusForm.name) }}
{{ form_row(genusForm.subFamily) }}
{{ form_row(genusForm.speciesCount) }}
OR
{{ form_row(genusForm.speciesCount, {
'label': 'Number of Species'
}) }}
{{ form_row(genusForm.funFact) }}
{{ form_row(genusForm.isPublished) }}
{{ form_row(genusForm.firstDiscoveredAt) }}
{{ form_end(genusForm) }}
>> We can use "addEventListener" function of form builder and bind data conditionally,
e.g.
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// ...
->add('country', 'count', array(...))
;
$builder->addEventListener(
FormEvents::PRE_BIND,
function(FormEvent $event) use($factory){
$data = $event->getData();
$form = $event->getForm();
$country = $data['country'];
$form->add('state', 'choice', array(
'choices' => array() // build state choices from country
))
}
);
}
Form themes are how we can control the markup used to render forms. The bootstrap_3_layout.html.twig template lives in the core of Symfony and now, our form markup will change to use HTML bits that live inside of it.
e.g. app/config/config.yml
twig:
form_themes:
- bootstrap_3_layout.html.twig
>> Creating a Date Picker form Field?
use Symfony\Component\Form\Extension\Core\Type\DateType;
e.g.
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('firstDiscoveredAt', DateType::class, ['attr' => ['class' => 'js-datepicker'],]);
}
>> Sharing Form Templates with include()?
{{ include('admin/genus/_form.html.twig') }}
>> Symfony Security?
Traditional login.
Facebook Authentication.
Github Authentication.
API Authentication with JSON web tokens.
Security has two big peaces.
Authentication -
- Who are you?
- Togh stuff.
- Login forms
- Social media authentication.
- API's
Authorisation -
- What permissions do you have?
>> authentication in symfony?
Open up app/config/security.yml. Security - especially authentication - is all configured here, there's one section that's more important than all the rest: firewalls.
e.g.
security:
firewalls:
# disables authentication for assets and the profiler, adapt it according to your needs
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
OR
firewalls:
main:
guard:
authenticators:
- app.security.login_form_authenticator
pattern: ^/
form_login:
provider: fos_userbundle
csrf_token_generator: security.csrf.token_manager
# if you are using Symfony < 2.8, use the following config instead:
# csrf_provider: form.csrf_provider
logout:
path: /logout
anonymous: true
providers:
our_users:
entity: { class: AppBundle\Entity\User, property: email }
>> How to add security in controller?
e.g.
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
class GenusAdminController extends Controller
{
/**
* @Route("/genus", name="admin_genus_list")
* @Security("is_granted('ROLE_ADMIN')")
*/
public function indexAction()
{
}
}
>> create Micro framework in Symfony via MicroKernelTrait?
using MicroKernelTrait You can build a Symfony app that's as small as one file.
e.g. app/LittleKernel.php
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
class LittleKernel extends Kernel
{
use MicroKernelTrait;
}
>> how to Loading External Routing/annotaion routing Files?
In kernel file we can add external routing file using RouteCollectionBuilder $routes->import() method.
e.g.
protected function configureRoutes(RouteCollectionBuilder $routes)
{
$routes->import(__DIR__.'/../src/AppBundle/Controller', '/', 'annotation');
}
//and add code in app/config/routing.yml
app:
resource: "@AppBundle/Controller/"
type: annotation
>> Autoloading?
Is the background machine it makes it possible to use PHP classes without using require or include statements.
>> Need of composer?
- Sharing want caring.
- Autoloading PHP classes.
- Dependecies?
- Where does this things go?
- Using Composer we can easy access to PHP libs from anywhere.
- Packagist (https://packagist.org) is used to find individual directory that we can download using composer.
- Composers main job is to download third-party libraries into a vendor directory.
- Add/install/download dependencies using composer we need composer.json file.
e.g. steps to use composer
- $ php composer.phar init // will use to initialize composer to add/create composer.json with dependencies packages.
- $ php composer.phar install // it reads composer.json and install dependecies into vendor
- To use downloaded dependecies packages we need to use/mention package in autoloading. using include vendor/autoload.php in project.
- compose.lock will record exact version of all libraries that it downloaded that exact moment. If compose.lock is present then composer install command will ignore composer.json file and reads all the information from the lock file. If you have made some changes in composer.json and you need to install dependencies then you need to use composer update command.
- $ php composer.phar update // always reads composer.json file and updates composer.lock with the new libraries and versions
- $ php composer.phar require // you can search for package you need and composer will automatically update composer.json for you.
>> What is Namespace?
- Adding namespace to class is like organizing file from one directory into subdirectory.
- a namespace uniquely identifies a set of names so that there is no ambiguity when objects having different origins but the same names are mixed together.
- It allows you to use the same function or class name in different parts of the same program without causing a name collision.
- a class of elements (e.g. addresses, file locations, etc.) in which each element has a name unique to that class, although it may be shared with elements in other classes.
- a namespace is a set of symbols that are used to organize objects of various kinds, so that these objects may be referred to by name
e.g.
namespace as a person's surname. If there are two people named "Nilesh" you can use their surnames to tell them apart.
>> List some namespaces in Symfony 3.3?
Symfony
Symfony\Bridge\Doctrine
Symfony\Bridge\Doctrine\Form
Symfony\Bridge\Doctrine\Form\Type
Symfony\Bridge\Doctrine\Logger
>> Where to set locale?
We can set the locale value in app/config/config.yml,
e.g.
framework:
default_locale: "%locale%"
//will replace to 'en' in same file with parameters key local value,
parameters: locale: en
>> Where to configure database connection?
The database connection configuration is writern in app/config/config.yml file and dynamic values are replaced from parameters.yml file
e.g.
//code in app/config/config.yml
doctrine:
dbal:
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
//code in app/config/parameters.yml.dist
parameters:
database_host: 127.0.0.1
database_port: ~
database_name: symfony
database_user: root
database_password: ~
>> How to get list of every parameters in symfony?
$ ./bin/console debug:container --parameters
>> Kernel parameters in symfony?
- debug:container gave us, find the group that starts with kernel.. You won't find these defined anywhere: they're baked right into Symfony and are some of the most useful parameters.
- kernel.debug - whether or not we're in debug mode.
- kernel.environment - enviorment.
- kernel.cache_dir - where Symfony stores its cache .
- kernel.root_dir - the app/ directory where the AppKernel class lives, Anytime you need to reference a path in your project, use kernel.root_dir and build the path from it.
e.g.
doctrine_cache:
providers:
my_markdown_cache:
type: %cache_type%
file_system:
directory: %kernel.cache_dir%/markdown_cache
>> if config.yml is so important - then what the heck is the point of all of these other files - like config_dev.yml, config_test.yml, parameters.yml, security.yml and services.yml. What is their purpose?
- The answer is environments.
- In Symfony, an environment is a set of configuration.
- Symfony has two environments by default: dev and prod. (Actually, there's a third environment called test that you might use while writing automated tests.)
- In the dev environment your code is booted with a lot of logging and debugging tools. But in the prod environment, that same code is booted with minimal logging and other configuration that makes everything fast.
>> how do we choose which environment we're using? And what environment have we been using so far?
- you will need to configure your web server to execute that file (app_dev.php for dev and app.php for production enviornment)
- The answer to that lives in the web directory, which is the document root and app.php, app_dev.php these files are beside in it.
- These two files - app.php and app_dev.php - are the keys. When you visit your app, you're always executing one of these files.
- Since we're using the server:run built-in web server: we're executing app_dev.php.
- That means that when we go to localhost:8000/genus/octopus that's equivalent to going to localhost:8000/app_dev.php/genus/octopus.
- So how can we switch to the prod environment? - Just copy that URL and change app_dev.php to app.php. Welcome to the prod environment: same app, but no web debug toolbar or other dev tool. in production you won't have this ugly app.php in your URL: you'll configure your web server to execute that file when nothing appears in the URL.
e.g.
$kernel = new AppKernel('dev', true); // is in app_dev.php i.e. dev enviormment, The second argument - true or false - is a debug flag and basically controls whether or not errors should be shown.
$kernel = new AppKernel('prod', false); // is in app.php i.e. production enviormment, The second argument - true or false - is a debug flag and basically controls whether or not errors should be shown.
>> what do these dev and prod strings do?
when Symfony boots, it loads only one configuration file for the entire system. it's not config.yml file but it depends on enviroment like app/config/config_dev.yml is for dev enviorment and app/config/config_prod.yml is for production enviormrnt. both of these files first imports: - { resource: config.yml } and after that it overrides any configuration that's special for the dev/prod environment.
>> How to disable markdown cache for dev enviorment?
Copy the doctrine_cache from config.yml and paste it into config_dev.yml. Next, change type from file_system to array, The array type is basically a "fake" cache: it won't ever store anything.
e.g.
doctrine_cache:
providers:
my_markdown_cache:
type: array
>> How to Clearing prod Cache?
$ ./bin/console cache:clear --env=prod
e.g.
If we need to change that "app/config/config.yml" thousands_separator from dot back to a comma in production
twig:
number_format:
thousands_separator: ','
Do the changes and then clear cache using $ ./bin/console cache:clear --env=prod command
>> What is use of services.yml, security.yml, parameter.yml? So where is parameters.yml loaded?
- At the top of app/config/config.yml parameters.yml imported, along with security.yml and services.yml files.
- The key point is that all of the files are just loading each other.
- parameters.yml - holds any configuration that will be different from one machine where the code is deployed to another. we use parameters in config.yml, This allows us to isolate all the machine-specific configuration to parameters.yml. parameters.yml is not committed to the repository.
- Due to a post-install command in your composer.json, after running composer install, Symfony will read parameters.yml.dist and ask you to fill in any values that are missing from parameters.yml
e.g.
your database password is most likely not the same as my database password and hopefully not the same as the production database password.
>> Doctrine and how to consume ReSTFUL api?
Doctrine is a database access layer.
You don't want to access a database, but apis.
You can still create an Entity, but then as a simple object that doesn't have to extend our implement anything (a popo).
It should have a Repository that implements all the CRUD methods.
In this case calls to the API instead of the database.
I'd create an interface for that.
It doesn't have to feel different for your application to use, except that you must take into account everywhere that a micro service might not respond.
>> Symfony start server on different port?
By default, the web server listens on port 8000 on the loopback device. You can change the socket passing an IP address and a port as a command-line argument:
$ php bin/console server:start 192.168.0.1:8080
You can use the server:status command to check if a web server is listening on a certain socket:
$ php bin/console server:status
$ php bin/console server:status 192.168.0.1:8080
Stop server
$ php bin/console server:stop 192.168.0.1:8080
>> What is Symfony?
Symfony is a PHP framework and a set of reusable components/libraries.
>> What are benefits of Symfony?
- Fast development
- MVC Pattern
- Unlimited flexibility
- Expandable
- Stable and sustainable
- Ease of use.
>> What is current Stable version of Symfony?
Version: 3.3, Manintain until: Jumly 2018
>> What is minimum PHP Version requirement for Symfony?
Symfony 3.3 requires PHP 5.5.9 or higher to run
>> How to concatenate strings in twig? (~)
{{ 'http://' ~ app.request.host }}
>> How to render a DateTime object in a Twig template?
{{ game.gameDate|date('Y-m-d') }}
>> How to var_dump variables in twig templates?
{{ dump(user) }}
>> How to get the request parameters in symfony2/3?
$name=$request->query->get('name');
How to get the request parameters in symfony2/3?
$request = $this->container->get('request');
$name=$request->query->get('name');
>> How to get list of all installed packages in composer?
composer global show
>> What is offical website URL of Symfony?
http://www.symfony.com
>> What is offical Github URL of Symfony?
https://github.com/symfony/symfony
>> How to create controller in Symfony2/3?
File Location: src/AppBundle/Controller/UserController.php
e.g.
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class UserController extends Controller
{}
>> How to create Action of controller in Symfony2?
e.g.
Add following code inside UserController.php
public function indexAction()
{
return $this->render('user/index.html.twig', [ ]);
}
>> What is format of view file?
File Location: app/Resources/views/user/index.html.twig
e.g.
{% extends 'base.html.twig' %}
{% block body %}
<h1>
Welcome to Symfony2</h1>
{# ... #}
{% endblock %}
>> How to get current route in Symfony?
$request = $this->container->get('request');
$currentRouteName = $request->get('_route');
>> The end product of a controller in Symfony is always the same – what is it?
Symfony2 Response object
>> The controller in Symfony creates a new Response object, whose first argument is the?
content that should be used in the response
>> In order to use the render() method in Symfony, your controller must extend the?
Controller class
>> A _____ defines the URL (e.g. /about) to your page and specifies a controller (which is a PHP function) that Symfony2 should execute
when the URL of an incoming request matches the route path?
route
>> A controller in Symfony is a.
a PHP function
>> Controllers are also called as ______
Actions
>> What are the common tasks performed by a Controller in Symfony?
A controller can do virtually anything. Some of the basic tasks done by a controller are redirecting, forwarding, rendering templates and accessing core services.
>> What is the goal of routing in Symfony?
The goal of the Symfony routing system is to parse a URL and determine which controller should be executed.
>> When Symfony denies the user access, what happens?
When Symfony denies the user access, the user sees an error screen and receives a 403 HTTP status code
>> The Request class symfony is a simple object-oriented representation of the?
HTTP request message
>> Symfony2 packages called ____________, which are fully functional applications that include the Symfony2 core libraries, a selection of useful bundles.
distributions
>> How to remove special characters from string?
echo preg_replace('/[^A-Za-z0-9\-]/', '', $string);
>> Difference between Symfony 2, 3 and 4.
>> Data Flow Diagram?
>> Database design Schema?
>> Access control/security in symfony?
>> SF (FOS) guard bundle in symfony? is used for authentication/login/registration in symfony.
>> difference between symfony 2 and 3?
>> Shall we use symfony bundles to other projects?
>> Authentication process in symfony?
>> Talking to database.
>> Using forms.
>> Setting up Security.
>> Handling API input & Validations.
>> How and why register your services.
>> What kind of configuration used in symfony?
>> How should we declare new service in yml or How to create and call service?
>> Service oriented architecture.
>> What is fragments in symfony?
Comments
Post a Comment