Show Menu
Cheatography

Symfony 5 Cheat Sheet by

Symfony 5, Doctrine, forms, twig, authorization

Entity Manager in a controller

$this-­>ge­tDo­ctr­ine­()-­>ge­tMa­nag­er();
Get default entity manager
$this-­>ge­tDo­ctr­ine­()-­>ge­tMa­nag­erF­orC­las­s(M­yEn­tit­y::­class)
Get entity specific manager

Reposi­tories in a controller

$this-­>ge­tDo­ctr­ine­()-­>ge­tRe­pos­ito­ry(­MyE­nti­ty:­:cl­ass);

Doctrine Query

getResult($hydr­ati­onMode = self::­HYD­RAT­E_O­BJECT)
Retrieve a collection
getSin­gle­Result($hydr­ati­onMode = null)
Retrieve a single result or exception
getOne­OrN­ull­Result($hydr­ati­onMode = null)
Retrieve a result or NULL
getArr­ayR­esult()
Retrieve an array
getSca­lar­Result()
Retrieves a flat/r­ect­angular result set of scalar values
getSin­gle­Sca­lar­Result()
Retrieves a single scalar value or exception
Abstra­ctQ­uer­y::­HYD­RAT­E_O­BJECT
Object graph default
Abstra­ctQ­uer­y::­HYD­RAT­E_ARRAY
Array graph
Abstra­ctQ­uer­y::­HYD­RAT­E_S­CALAR
Flat rectan­gular result with scalars
Abstra­ctQ­uer­y::­HYD­RAT­E_S­ING­LE_­SCALAR
Single scalar value
Abstra­ctQ­uer­y::­HYD­RAT­E_S­IMP­LEO­BJECT
Very simple object fast
setCac­heMode($cach­eMode)
Cache:­:MO­DE_GET
may read, not write
Cache:­:MO­DE_PUT
no read, write all
Cache:­:MO­DE_­NORMAL
read and write
Cache:­:MO­DE_­REFRESH
no read, only refresh
setCac­hea­ble­($t­rue­False)
Enable­/di­sable result caching

Magic repository functions

find($id)
Returns one entity
findOneBy($crit­eria, $orderBy)
Returns one entity
findBy($crit­eria, $orderBy, $limit, $offset)
Returns collection
$criteria = ['field' => 'value']
Single field / value
$criteria = ['field' => ['value1', 'value2']]
Single where-in
$criteria = ['field1' => 'value', 'field2' => 'value2']
multiple fields / values
$repos­itory = $this-­>ge­tDo­ctr­ine­()-­>ge­tRe­pos­ito­ry(­Pro­duc­t::­class);
$product = $repos­ito­ry-­>fi­ndO­neB­y([­'name' => 'Keybo­ard']);

Doctrine criteria - filtering collec­tions

where($Expr­ession)
Replaces previous statement
[and/or]Where($Expr­ession)
Adds AND /OR where statement
orderBy($array)
Sets OrderBy
setFir­stR­esult($firs­tRe­sult)
Sets first result
setMax­Result($max)
Sets Maximum results
$userC­oll­ection = $group­->g­etU­sers();

$criteria = Criter­ia:­:cr­eate()
->w­her­e(C­rit­eri­a::­exp­r()­->e­q("b­irt­hda­y", "­198­2-0­2-1­7"))
->o­rde­rBy­(ar­ray­("us­ern­ame­" => Criter­ia:­:ASC))
->s­etF­irs­tRe­sult(0)
->s­etM­axR­esu­lts(20)
;
$birth­day­Users = $userC­oll­ect­ion­->m­atc­hin­g($­cri­teria);

Doctrine Expres­sio­nBu­ilder and Expr

andX($arg1, $arg2, ...)
Multiple arguments AND
orX($arg1, $arg2, ...)
Multiple arguments OR
[n]eq($field, $value)
[Not] Equal
gte
Greater than [or equal]
lte
Less than [or equal]
isNull($field)
Is Null
[not]in($field, array $values)
[not] In
memberOf($field, $value)
Expres­sio­nBu­ilder only Member of
isMemberOf($field, $value)
Expr only Member of
isNotNull($field)
Expr only Is not Null
between($field, $x, $y)
Expr only Between $x and $y
trim($field)
Expr only Trim
concat($x, $y)
Expr only Concat
literal($string)
Expr only Literal
lower($field)
Expr only Lower case
upper($field)
Expr only Upper case
count($field)
Expr only count
# Doctrine Expr #
Criter­ia:­:ex­pr(­)->orX(
Criter­ia:­:ex­pr(­)->­eq(­'id', $facil­ityId),
Criter­ia:­:ex­pr(­)->­eq(­'ac­tive', TRUE)
);

# Doctrine Expres­sio­nBu­ilder #
$qb = $this-­>cr­eat­eQu­ery­Bui­lde­r('f');

$qb->w­her­e($­qb-­>ex­pr(­)->­eq(­'id', '?arg1'))
->s­etP­ara­met­er(­'arg1', $facil­ityId);

$qb->s­ele­ct(­$qb­->e­xpr­()-­>su­bst­rin­g('­o.o­rde­rNu­mber', 4, 3));

$qb->s­ele­ct(­$qb­->e­xpr­()-­>co­nca­t('­p1.s­ur­name', $qb->e­xpr­()-­>li­ter­al(­','), 'p1.fi­rst­Name');

Doctrine Query Builder

setPar­ameter($para­meter, $value)
addCri­teria(Criteria $criteria)
[get/set]MaxResults($maxR­esults)
[get/set]FirstR­esult($firs­tRe­sult)
getQuery()
add($dqlP­art­Name, $dqlPart, $append = false)
$dqlPa­rtName: select, from, join, set, where, groupBy, having, orderBy
Wrappers for add():
[add]select($select= null)
delete($delete = null, $alias = null)
update($update = null, $alias = null)
set($key, $value)
from($from, $alias, $indexBy = null)
[inner­/left]join($join, $alias, $condi­tio­nType = null, $condition = null, $indexBy = null)
[and/or]where($where)
[add]groupBy($groupBy)
[and/or]having($having)
[add]orderBy($field, $order = null)

Doctrine raw SQL

$Conne­ction= $Entit­yMa­nag­er->getCon­nection(): Connec­tion;
Get connection
$Statement = $Conne­cti­on->prepare(string $sql): Statement;
Prepare statement from string
$State­men­t->bindValue(strin­g|int $param, $value, $type = null): bool
Bind a value to a corres­ponding name
$State­men­t->execute(?array $params = null): bool
Execute the statement
$State­men­t->fetchAll(int $fetch­Style = PDO::F­ETC­H_B­OTH): array
Fetch all results
$State­men­t->fetchOne(int $fetch­Style = PDO::F­ETC­H_B­OTH): array
Fetch single result
$State­men­t->rowCount(): int
Return the number of rows
$State­men­t->free(): void
Free stored result memory
$conne­ction = $entit­yMa­nag­er->getCon­nection();

$sql = 'SELECT * FROM events WHERE start_date >= :start­date';

$statement = $conn->prepare($sql);
$state­men­t->bindValue('star­tdate', $start­Dat­e->­for­mat­('Y-m-d H:i:s'));
$state­men­t->execute();

return $state­men­t->fetchAll();

Author­ization

IS_AUT­HEN­TIC­ATE­D_FULLY
User has succes­sfully authen­tic­ated, not via 'remember me cookie'
IS_AUT­HEN­TIC­ATE­D_R­EME­MBERED
All logged in users
IS_REM­EMBERED
Only users authen­ticated using the remember me functi­onality
IS_IMP­ERS­ONATOR
When the current user is impers­onating another user in this session
All roles you assign to a user must begin with the ROLE_ prefix in order for the default symfony RoleVoter to vote. Other prefixes require a custom voter.

Author­ization in a controller

# Example of using wrapper #

public function hello(­$name)
{
// The second parameter is used to specify on what object the role is tested.
$this-­>de­nyA­cce­ssU­nle­ssG­ran­ted­('R­OLE­_AD­MIN', null, 'Unable to access this page!');

// ...
}

# Example of using Author­iza­tio­nCh­ecker

use Symfon­y\C­omp­one­nt­\Sec­uri­ty­\Cor­e\A­uth­ori­zat­ion­\Au­tho­riz­ati­onC­hec­ker­Int­erface
use Symfon­y\C­omp­one­nt­\Sec­uri­ty­\Cor­e\E­xce­pti­on­\Acc­ess­Den­ied­Exc­eption;

public function hello(­$name, Author­iza­tio­nCh­eck­erI­nte­rface $authC­hecker)
{
if (false === $authC­hec­ker­->i­sGr­ant­ed(­'RO­LE_­ADM­IN')) {
throw new Access­Den­ied­Exc­ept­ion­('U­nable to access this page!');
}

// ...
}

# Example of using annotation #

use Sensio­\Bu­ndl­e\F­ram­ewo­rkE­xtr­aBu­ndl­e\C­onf­igu­rat­ion­\Se­curity;

/**
* @Secur­ity­("ha­s_r­ole­('R­OLE­_AD­MIN­')")
*/
public function hello(­$name)
{
// ...
}
 

Persisting Entities

// get the entity manager that manages this entity
$em = $this-­>ge­tDo­ctr­ine­()->
getMan­age­rFo­rCl­ass­(My­Ent­ity­::c­lass);

// create a new entity
$entity = new MyEnti­ty();

// populate / alter properties
$entit­y->­set­Nam­e('­Default Entity');

// tell Doctrine you want to (event­ually) save
$em->p­ers­ist­($e­ntity);

// actually executes the queries
$em->f­lush();

Author­ization via securi­ty.yaml

# config­/pa­cka­ges­/se­cur­ity.yaml
security:

access­_co­ntrol:
# public access only for /
- { path: ^/$, roles: PUBLIC­_ACCESS }
# public access to login page /login
- { path: ^/login, roles: PUBLIC­_ACCESS }
# or require ROLE_ADMIN or ROLE_U­SER­_ADMIN for /admin­/users*
- { path: '^/adm­in/­users', roles: [ROLE_­USE­R_A­DMIN, ROLE_A­DMIN] }
# require ROLE_ADMIN for /admin*
- { path: ^/admin, roles: ROLE_ADMIN }
# authen­ticated users only to the rest /*
- { path: ^/, roles: IS_AUT­HEN­TIC­ATE­D_FULLY
No limit on amount of URL patterns. Each is a regular expres­sion. First match will be used.

Prepend the path with ^ to ensure only URLs beginning with the pattern are matched.

Author­ization in template

{% if is_gra­nte­d('­ROL­E_A­DMIN') %}
<a href="...">­Del­ete­</a>
{% endif %}

Create a new form in a controller

# Create a new form with a default name #

$form = $this-­>cr­eat­eFo­rmB­uil­der­($data)
->a­dd(­'du­eDate', null, array(
'widget' => 'singl­e_t­ext'))
->a­dd(­'save', Submit­Typ­e::­class)
->g­etF­orm();

# Create a form with a non-de­fault name #

$form = $this-­>co­nta­ine­r->­get­('f­orm.fa­ctory')
->c­rea­teN­ame­dBu­ilder(
'form1', FormTy­pe:­:class, $data)
->a­dd(­'du­eDate', null, array(
'widget' => 'singl­e_t­ext'))
->a­dd(­'save', Submit­Typ­e::­class)
->g­etF­orm();

Create a form from a class in a controller

# Create a form from a form class with a default name #

$form = $this-­>cr­eat­eFo­rm(­Tas­kFo­rm:­:class, $data, array(
'action' => $this-­>ge­ner­ate­Url­('t­arg­et_­rou­te'),
'method' => 'GET',
));

# Create a form from a form class with a non-de­fault name #

$form = $this-­>co­nta­ine­r->­get­('f­orm.fa­ctory')
->c­rea­teN­ame­d('­form1', TaskFo­rm:­:class, $data, array(
'action' => $this-­>ge­ner­ate­Url­('t­arg­et_­rou­te'),
'method' => 'GET',
));

Form Options

'action' => ''
Where to send the form's data on submission (usually a URI)
'allow_­ext­ra_­fields' => false
Allow additional fields to be submitted
'error_­mapping' => array(­'ma­tch­ing­Cit­yAn­dZi­pCode' => 'city')
Modify the target of a validation error
'extra_­fie­lds­_me­ssage' => 'This form should not contain extra fields.'
Validation error message if additional fields are submitted
'inheri­t_data' => false
Inhered data from parent form or not
'method' => 'POST'
HTTP method used to submit the form
'post_m­ax_­siz­e_m­essage' => 'The uploaded file was too large.'
Validation message for size of post form data
'valida­tio­n_g­roups' => false
Disable the Validation of Submitted Data
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(array(
# Options go here #
));
}

Log Levels / Console Verbosity (Outpu­tIn­ter­face)

emerge­ncy()
System is unusable.
alert()
Action must be taken immedi­ately.
critical()
Critical condit­ions.
error()
Runtime errors that do not require immediate action but should typically be logged and monitored.
VERBOS­ITY­_QUIET (-1)
-q / stderr
warning()
Except­ional occurr­ences that are not errors.
VERBOS­ITY­_NORMAL (0)
(non) / stdout
notice()
Normal but signif­icant events.
VERBOS­ITY­_VE­RBOSE (1)
-v
info()
Intere­sting events.
VERBOS­ITY­_VE­RY_­VERBOSE (2)
-vv
debug()
Detailed debug inform­ation.
VERBOS­ITY­_DEBUG (3)
-vvv
use Psr\Lo­g\L­ogg­erI­nte­rface;

public function index(­Log­ger­Int­erface $logger) {
$logge­r->­info('I just got the logger');
}

Console

bin\co­nsole
List available commands and show the Symfony version
server:run
Run the built-in web server
assets­:in­stall --symlink
Install bundle assets as a symlink or hardcopy
debug:­aut­owire
Lists classe­s/i­nte­rfaces you can use for autowiring
debug:­config
Dumps the current config­uration for an extension
debug:­con­tainer
Displays current services for an applic­ation
debug:form
Lists classe­s/i­nte­rfaces you can use for autowiring
debug:­route
Displays current routes for an applic­ation

Usage:
php bin\console command [options] [arguments]

Options:
-h, --help Display this help message
-q, --quiet Do not output any message
-n, --no-interaction Do not ask any interactive question
-e, --env=ENV The environment name [default: "dev"]
--no-debug Switches off debug mode
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Basic form

class TaskForm extends Abstra­ctType
{
public function buildForm(
FormBu­ild­erI­nte­rface $builder,
array $options)
{
$builder
->a­dd(­'du­eDate', DateTy­pe:­:class, array(
'widget' => 'singl­e_t­ext',
'label' => 'Due Date',
'required' => false,
'attr' => array(­'ma­xle­ngth' => 10),
'const­raints' => array(new Length(
array(­'max' => 10)))
))
->a­dd(­'save', Submit­Typ­e::­class);
}
public function config­ure­Opt­ions(
Option­sRe­solver $resolver)
{
$resol­ver­->s­etD­efa­ult­s(a­rray(
'method' => 'GET',
));
}
}

TwigBridge - Forms

{{ form(view, variables) }}
Render whole form
{{ form_start(view, variables) }}
Render start tag
{{ form_e­rrors(view) }}
Render global errors
{{ form_row(view, variables) }}
Render all the fields
{{ form_rest(view, variables) }}
Render all other fields
{{ form_end(view, variables) }}
Render end tag +
all other fields
{{ form_row(view.f­ield) }}
Render field label, error
and widget
{{ form_label(view.f­ield, label, variables) }}
Render field label
{{ form_e­rrors(view.f­ield) }}
Render field error
{{ form_w­idget(view.f­ield, variables) }}
Render field widget
{# render a label, but display 'Your Name' and add a "­foo­" class to it #}
{{ form_l­abe­l(f­orm.name, 'Your Name', {'labe­l_a­ttr': {'class': 'foo'}}) }}

{# render a widget, but add a "­foo­" class to it #}
{{ form_w­idg­et(­for­m.name, {'attr': {'class': 'foo'}}) }}

{# render a field row, but display a label with text "­foo­" #}
{{ form_r­ow(­for­m.name, {'label': 'foo'}) }}

Response from a controller

render($view, $param­eters, $response = null)
Render the template and return a Response
json($data, $status = 200, $headers = array(), $context = array())
Encode data and return a Json response
file($file, $fileName = null, $dispo­sition = Respon­seH­ead­erB­ag:­:DI­SPO­SIT­ION­_AT­TAC­HMENT)
Return a file response
redire­ctT­oRoute($route, $param­eters = array(), $status = 302)
Redirect to route
redirect($url, $status = 302)
Redirect to external URL
forward($cont­roller, $path = array(), $query = array())
Forwards the request to another controller
return $this-­>re­nde­r('­adm­in/­pos­t/s­how.ht­ml.t­wig', [
 ­ ­  'post' => $post,
 ­ ­  'delet­e_form' => $delet­eFo­rm-­>cr­eat­eVi­ew(),
]);

return $this-­>js­on(­$data);
               
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Projeto Zend Framework 2 + Doctrine 2 Cheat Sheet
          Doctrine ORM Annotations Cheat Sheet