Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
66 views6 pages

Symfony 5

This document provides a cheat sheet summary of key Doctrine ORM concepts in Symfony including: 1) How to get the entity manager and repositories in controllers. 2) How to perform basic CRUD operations and queries using the entity manager, repositories, and QueryBuilder. 3) Details on hydration modes, caching, criteria, expressions, and raw SQL queries.

Uploaded by

samimahjoub090
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views6 pages

Symfony 5

This document provides a cheat sheet summary of key Doctrine ORM concepts in Symfony including: 1) How to get the entity manager and repositories in controllers. 2) How to perform basic CRUD operations and queries using the entity manager, repositories, and QueryBuilder. 3) Details on hydration modes, caching, criteria, expressions, and raw SQL queries.

Uploaded by

samimahjoub090
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Symfony 5 Cheat Sheet

by Marcel Berteler (pluk77) via cheatography.com/55947/cs/14851/

Entity Manager in a controller Doctrine Query (cont)

$this-​>ge​tDo​ctr​ine​()-​>ge​tMa​nag​er(); Get default entity Cache:​:MO​DE_​REFRESH no read, only refresh


manager setCac​hea​ble​($t​rue​False) Enable​/di​sable result caching
$this-​>ge​tDo​ctr​ine​()-​>ge​tMa​nag​erF​orC​las​‐ Get entity specific
s(M​yEn​tit​y::​class) manager Magic repository functions

find ($id) Returns one entity


Reposi​tories in a controller
findOneBy($crit​eria, $orderBy) Returns one entity
$this-​>ge​tDo​ctr​ine​()-​>ge​tRe​pos​ito​ry(​MyE​nti​ty:​:cl​ass);
findBy ($crit​eria, $orderBy, $limit, $offset) Returns collection
$criteria = ['field' => 'value'] Single field / value
Doctrine Query
$criteria = ['field' => ['value1', 'value2']] Single where-in
getResult($hydr​ati​onMode = Retrieve a collection
self::​HYD​RAT​E_O​BJECT) $criteria = ['field1' => 'value', 'field2' => multiple fields /
'value2'] values
getSin​gle​Result($hydr​ati​onMode Retrieve a single result or
= null) exception $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']);
getOne​OrN​ull​Result($hydr​ati​‐ Retrieve a result or NULL
onMode = null)
Doctrine criteria - filtering collec​tions
getArr​ayR​esult () Retrieve an array
where($Expr​ession) Replaces previous statement
getSca​lar​Result() Retrieves a flat/r​ect​angular
result set of scalar values [and/or]Where($Expr​ession) Adds AND /OR where statement

getSin​gle​Sca​lar​Result() Retrieves a single scalar value orderBy($array) Sets OrderBy


or exception setFir​stR​esult($firs​tRe​sult) Sets first result
Abstra​ctQ​uer​y::​HYD​RAT​E_O​‐ Object graph default setMax​Result($max) Sets Maximum results
BJECT
$userC​oll​ection = $group​->g​etU​sers();
Abstra​ctQ​uer​y::​HYD​RAT​‐ Array graph
E_ARRAY $criteria = Criter​ia:​:cr​eate()
Abstra​ctQ​uer​y::​HYD​RAT​E_S​‐ Flat rectan​gular result with ->w​her​e(C​rit​eri​a::​exp​r()​->e​q("b​irt​hda​y", "​198​2-0​2-1​7"))
CALAR scalars ->o​rde​rBy​(ar​ray​("us​ern​ame​" => Criter​ia:​:ASC))
->s​etF​irs​tRe​sult(0)
Abstra​ctQ​uer​y::​HYD​RAT​E_S​‐ Single scalar value
->s​etM​axR​esu​lts(20)
ING​LE_​SCALAR
;
Abstra​ctQ​uer​y::​HYD​RAT​E_S​‐ Very simple object fast
$birth​day​Users = $userC​oll​ect​ion​->m​atc​hin​g($​cri​teria);
IMP​LEO​BJECT
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

By Marcel Berteler (pluk77) Published 18th April, 2023. Sponsored by Readable.com


cheatography.com/pluk77/ Last updated 10th May, 2023. Measure your website readability!
Page 1 of 6. https://readable.com
Symfony 5 Cheat Sheet
by Marcel Berteler (pluk77) via cheatography.com/55947/cs/14851/

Doctrine Expres​sio​nBu​ilder and Expr Doctrine Query Builder (cont)

andX ($arg1, $arg2, ...) Multiple arguments AND add($dqlP​art​Name, $dqlPart, $append = false)
orX($arg1, $arg2, ...) Multiple arguments OR $dqlPa​rtName: select, from, join, set, where, groupBy, having,
[n]eq($field, $value) [Not] Equal orderBy

gte Greater than [or equal] Wrappers for add():

lte Less than [or equal] [add]select($select= null)

isNull($field) Is Null delete($delete = null, $alias = null)

[not]in ($field, array $values) [not] In update ($update = null, $alias = null)

memberOf($field, $value) Expres​sio​nBu​ilder only Member of set ($key, $value)

isMemberOf($field, $value) Expr only Member of from($from, $alias, $indexBy = null)

isNotNull($field) Expr only Is not Null [inner​/left]join($join, $alias, $condi​tio​nType = null, $condition = null,
$indexBy = null)
between ($field, $x, $y) Expr only Between $x and $y
[and/or]where($where)
trim($field) Expr only Trim
[add]groupBy($groupBy)
concat($x, $y) Expr only Concat
[and/or]having($having)
literal($string) Expr only Literal
[add]orderBy($field, $order = null)
lower($field) Expr only Lower case
upper($field) Expr only Upper case
Doctrine raw SQL
count($field) Expr only count
$Conne​ction= $Entit​yMa​nag​er->getCon​‐ Get connection
# Doctrine Expr # nection(): Connec​tion;
Criter​ia:​:ex​pr(​)->orX(
$Statement = $Conne​cti​on- Prepare statement
Criter​ia:​:ex​pr(​)->​eq(​'id', $facil​ityId),
>prepare(string $sql): Statement; from string
Criter​ia:​:ex​pr(​)->​eq(​'ac​tive', TRUE)
$State​men​t->bindValue(strin​g|int $param, Bind a value to a
);
$value, $type = null): bool corres​ponding name

# Doctrine Expres​sio​nBu​ilder # $State​men​t->execute(?array $params = Execute the statement


$qb = $this-​>cr​eat​eQu​ery​Bui​lde​r('f'); null): bool
$State​men​t->fetchAll(int $fetch​Style = Fetch all results
$qb->w​her​e($​qb-​>ex​pr(​)->​eq(​'id', '?arg1')) PDO::F​ETC​H_B​OTH): array
->s​etP​ara​met​er(​'arg1', $facil​ityId); $State​men​t->fetchOne (int $fetch​Style = Fetch single result
PDO::F​ETC​H_B​OTH): array
$qb->s​ele​ct(​$qb​->e​xpr​()-​>su​bst​rin​g('​o.o​rde​rNu​mber', 4, 3));
$State​men​t->rowCount(): int Return the number of
rows
$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()

By Marcel Berteler (pluk77) Published 18th April, 2023. Sponsored by Readable.com


cheatography.com/pluk77/ Last updated 10th May, 2023. Measure your website readability!
Page 2 of 6. https://readable.com
Symfony 5 Cheat Sheet
by Marcel Berteler (pluk77) via cheatography.com/55947/cs/14851/

Doctrine raw SQL (cont) Author​ization in a controller (cont)

$State​men​t->free(): void Free stored result memory 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!');
$conne​ction = $entit​yMa​nag​er->getCon​nection();
}
// ...
$sql = 'SELECT * FROM events WHERE start_date >= :start​date';
}
# Example of using annotation #
$statement = $conn->prepare($sql);
use Sensio​\Bu​ndl​e\F​ram​ewo​rkE​xtr​aBu​ndl​e\C​onf​igu​rat​ion​\Se​curity;
$state​men​t->bindValue('star​tdate', $start​Dat​e->​for​mat​('Y-m-d H:i:s'));
/**
$state​men​t->execute();
* @Secur​ity​("ha​s_r​ole​('R​OLE​_AD​MIN​')")
*/
return $state​men​t->fetchAll();
public function hello(​$name)
{
Author​ization
// ...
IS_AUT​HEN​TIC​ATE​‐ User has succes​sfully authen​tic​ated, not
}
D_FULLY via 'remember me cookie'
IS_AUT​HEN​TIC​ATE​‐ All logged in users Persisting Entities
D_R​EME​MBERED
// get the entity manager that manages this entity
IS_REM​EMBERED Only users authen​ticated using the $em = $this-​>ge​tDo​ctr​ine​()->
remember me functi​onality getMan​age​rFo​rCl​ass​(My​Ent​ity​::c​lass);
IS_IMP​ERS​ONATOR When the current user is impers​onating // create a new entity
another user in this session $entity = new MyEnti​ty();
// populate / alter properties
All roles you assign to a user must begin with the ROLE_ prefix in
$entit​y->​set​Nam​e('​Default Entity');
order for the default symfony RoleVoter to vote. Other prefixes
// tell Doctrine you want to (event​ually) save
require a custom voter.
$em->p​ers​ist​($e​ntity);
// actually executes the queries
Author​ization in a controller
$em->f​lush();
# Example of using wrapper #
public function hello(​$name)
Author​ization via securi​ty.yaml
{
# config​/pa​cka​ges​/se​cur​ity.yaml
// The second parameter is used to specify on what object the role is
security:
tested.
access​_co​ntrol:
$this-​>de​nyA​cce​ssU​nle​ssG​ran​ted​('R​OLE​_AD​MIN', null, 'Unable to
# public access only for /
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)
{

By Marcel Berteler (pluk77) Published 18th April, 2023. Sponsored by Readable.com


cheatography.com/pluk77/ Last updated 10th May, 2023. Measure your website readability!
Page 3 of 6. https://readable.com
Symfony 5 Cheat Sheet
by Marcel Berteler (pluk77) via cheatography.com/55947/cs/14851/

Author​ization via securi​ty.yaml (cont) Create a form from a class in a controller

- { path: ^/$, roles: PUBLIC​_ACCESS } # Create a form from a form class with a default name #
# public access to login page /login $form = $this-​>cr​eat​eFo​rm(​Tas​kFo​rm:​:class, $data, array(
- { path: ^/login, roles: PUBLIC​_ACCESS } 'action' => $this-​>ge​ner​ate​Url​('t​arg​et_​rou​te'),
# or require ROLE_ADMIN or ROLE_U​SER​_ADMIN for 'method' => 'GET',
/admin​/users* ));
- { path: '^/adm​in/​users', roles: [ROLE_​USE​R_A​DMIN, ROLE_A​‐ # Create a form from a form class with a non-de​fault name #
DMIN] } $form = $this-​>co​nta​ine​r->​get​('f​orm.fa​ctory')
# require ROLE_ADMIN for /admin* ->c​rea​teN​ame​d('​form1', TaskFo​rm:​:class, $data, array(
- { path: ^/admin, roles: ROLE_ADMIN } 'action' => $this-​>ge​ner​ate​Url​('t​arg​et_​rou​te'),
# authen​ticated users only to the rest /* 'method' => 'GET',
- { path: ^/, roles: IS_AUT​HEN​TIC​ATE​D_FULLY ));

No limit on amount of URL patterns. Each is a regular expres​sion.


Form Options
First match will be used.
'action' => '' Where to send the form's data
Prepend the path with ^ to ensure only URLs beginning with the on submission (usually a URI)
pattern are matched. 'allow_​ext​ra_​fields ' => false Allow additional fields to be
submitted
Author​ization in template
'error_​mapping' => array(​'ma​tch​‐ Modify the target of a validation
{% if is_gra​nte​d('​ROL​E_A​DMIN') %} ing​Cit​yAn​dZi​pCode' => 'city') error
<a href="...">​Del​ete​</a>
'extra_​fie​lds​_me​ssage ' => 'This Validation error message if
{% endif %}
form should not contain extra additional fields are submitted
fields.'
Create a new form in a controller
'inheri​t_data' => false Inhered data from parent form
# Create a new form with a default name # or not
$form = $this-​>cr​eat​eFo​rmB​uil​der​($data)
'method ' => 'POST' HTTP method used to submit
->a​dd(​'du​eDate', null, array(
the form
'widget' => 'singl​e_t​ext'))
'post_m​ax_​siz​e_m​essage' => 'The Validation message for size of
->a​dd(​'save', Submit​Typ​e::​class)
uploaded file was too large.' post form data
->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();

By Marcel Berteler (pluk77) Published 18th April, 2023. Sponsored by Readable.com


cheatography.com/pluk77/ Last updated 10th May, 2023. Measure your website readability!
Page 4 of 6. https://readable.com
Symfony 5 Cheat Sheet
by Marcel Berteler (pluk77) via cheatography.com/55947/cs/14851/

Form Options (cont) Console

'valida​tio​n_g​roups ' => Disable the Validation of Submitted bin\co​nsole List available commands and show the
false Data Symfony version

public function configureOptions(OptionsResolver $resolver) { server:run Run the built-in web server
$resolver->setDefaults(array( assets​:in​stall -- Install bundle assets as a symlink or hardcopy
# Options go here # symlink
));
debug:​aut​owire Lists classe​s/i​nte​rfaces you can use for
}
autowiring
debug:​config Dumps the current config​uration for an
Log Levels / Console Verbosity (Outpu​tIn​ter​face)
extension
emerge​‐ System is unusable.
debug:​con​tainer Displays current services for an applic​ation
ncy()
debug:form Lists classe​s/i​nte​rfaces you can use for
alert() Action must be taken immedi​ately.
autowiring
critical() Critical condit​ions.
debug:​route Displays current routes for an applic​ation
error() Runtime errors that do not VERBOS​‐ -q /
require immediate action but ITY​_QUIET stderr
Usage:
should typically be logged and (-1)
php bin\console command [options] [arguments]
monitored.
warning() Except​ional occurr​ences that are VERBOS​‐ (non)
Options:
not errors. ITY​‐ /
-h, --help Display this help message
_NORMAL stdout
-q, --quiet Do not output any message
(0)
-n, --no-interaction Do not ask any interactive question
notice() Normal but signif​icant events. VERBOS​‐ -v -e, --env=ENV The environment name [default: "dev"]
ITY​_VE​‐ --no-debug Switches off debug mode
RBOSE (1) -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for
info() Intere​sting events. VERBOS​‐ -vv normal output, 2 for more verbose output and 3 for debug
ITY​_VE​‐
RY_​‐ Basic form
VERBOSE class TaskForm extends Abstra​ctType
(2) {
debug() Detailed debug inform​ation. VERBOS​‐ -vvv public function buildForm(
ITY​‐ FormBu​ild​erI​nte​rface $builder,
_DEBUG array $options)
(3) {
$builder
use Psr\Lo​g\L​ogg​erI​nte​rface;
->a​dd(​'du​eDate', DateTy​pe:​:class, array(
'widget' => 'singl​e_t​ext',
public function index(​Log​ger​Int​erface $logger) {
$logge​r->​info('I just got the logger');
}

By Marcel Berteler (pluk77) Published 18th April, 2023. Sponsored by Readable.com


cheatography.com/pluk77/ Last updated 10th May, 2023. Measure your website readability!
Page 5 of 6. https://readable.com
Symfony 5 Cheat Sheet
by Marcel Berteler (pluk77) via cheatography.com/55947/cs/14851/

Basic form (cont) TwigBridge - Forms (cont)

'label' => 'Due Date', {{ form_e​rrors (view.f​ield) }} Render field error


'required' => false, {{ form_w​idget(view.f​ield, variables) }} Render field widget
'attr' => array(​'ma​xle​ngth' => 10),
{# render a label, but display 'Your Name' and add a "​foo​" class to it
'const​raints' => array(new Length(
#}
array(​'max' => 10)))
{{ form_l​abe​l(f​orm.name, 'Your Name', {'labe​l_a​ttr': {'class': 'foo'}}) }}
))
->a​dd(​'save', Submit​Typ​e::​class);
{# render a widget, but add a "​foo​" class to it #}
}
{{ form_w​idg​et(​for​m.name, {'attr': {'class': 'foo'}}) }}
public function config​ure​Opt​ions(
Option​sRe​solver $resolver)
{# render a field row, but display a label with text "​foo​" #}
{
{{ form_r​ow(​for​m.name, {'label': 'foo'}) }}
$resol​ver​->s​etD​efa​ult​s(a​rray(
'method' => 'GET',
Response from a controller
));
} render($view, $param​eters, $response = null) Render the template
} and return a
Response
TwigBridge - Forms json($data, $status = 200, $headers = array(), Encode data and
{{ form(view, variables) }} Render whole form $context = array()) return a Json
response
{{ form_start(view, variables) }} Render start tag
file($file, $fileName = null, $dispo​sition = Return a file
{{ form_e​rrors (view) }} Render global errors
Respon​seH​ead​erB​ag:​:DI​SPO​SIT​ION​_AT​‐ response
{{ form_row(view, variables) }} Render all the fields
TAC​HMENT)
{{ form_rest(view, variables) }} Render all other fields
redire​ctT​oRoute($route, $param​eters = Redirect to route
{{ form_end(view, variables) }} Render end tag + array(), $status = 302)
all other fields
redirect ($url, $status = 302) Redirect to external
{{ form_row(view.f​ield) }} Render field label, error URL
and widget
forward ($cont​roller, $path = array(), $query = Forwards the
{{ form_label (view.f​ield, label, variables) }} Render field label array()) 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);

By Marcel Berteler (pluk77) Published 18th April, 2023. Sponsored by Readable.com


cheatography.com/pluk77/ Last updated 10th May, 2023. Measure your website readability!
Page 6 of 6. https://readable.com

You might also like