0% found this document useful (0 votes)
44 views

Symfony 4 Cheat Sheet: by Via

This document provides a cheat sheet on using the Entity Manager, repositories, Doctrine Query Builder, and Doctrine queries in Symfony 4. It outlines how to get the entity manager, call repository methods to find entities, build queries with the query builder and set parameters, define hydration modes, enable caching, and persist entities with the entity manager. The cheat sheet also lists many Doctrine expression builder functions and criteria methods for filtering entity collections.

Uploaded by

losus007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Symfony 4 Cheat Sheet: by Via

This document provides a cheat sheet on using the Entity Manager, repositories, Doctrine Query Builder, and Doctrine queries in Symfony 4. It outlines how to get the entity manager, call repository methods to find entities, build queries with the query builder and set parameters, define hydration modes, enable caching, and persist entities with the entity manager. The cheat sheet also lists many Doctrine expression builder functions and criteria methods for filtering entity collections.

Uploaded by

losus007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Symfony 4 Cheat Sheet

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

Entity Manager in a controller Reposi​tories in a controller

$this-​>ge​tDo​ctr​ine​()-​>ge​tMa​nag​er(); Get default entity $this-​>ge​tDo​ctr​ine​()-​>ge​tRe​pos​ito​ry(​MyE​nti​ty:​:cl​ass);


manager

$this-​>ge​tDo​ctr​ine​()-​>ge​tMa​nag​erF​orC​las​s(M​yEn​ Get entity specific Doctrine Expres​sio​nBu​ilder and Expr


tit​y::​class) manager
andX​ (​$arg1, $arg2, ...) Multiple arguments AND

orX​($​arg1, $arg2, ...) Multiple arguments OR


Magic repository functions
[n]e​q​($f​ield, $value) [Not] Equal
find​ ($id) Returns one entity
gt​[e]​($f​ield, $value) Greater than [or equal]
find​One​By​($​cri​teria, $orderBy) Returns one entity
lt​[e]​($f​ield, $value) Less than [or equal]
find​By​($​cri​teria, $orderBy, $limit, $offset) Returns collection
isNu​ll​($​field) Is Null
$criteria = ['field' => 'value'] Single field / value
[not]​in​(​$field, array $values) [not] In
$criteria = ['field' => ['value1', 'value2']] Single where-in
memb​erO​f ​($f​ield, $value) Expr​ess​ion​Builder only Member of
$criteria = ['field1' => 'value', 'field2' => 'value2'] multiple fields / values
isMe​mbe​rOf​(​$field, $value) Expr only Member of
$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']); isNo​tNu​ll​($​field) Expr only Is not Null

betw​een​(​$field, $x, $y) Expr only Between $x and $y


Doctrine criteria - filtering collec​tions
trim​(​$field) Expr only Trim
wher​e​($E​xpr​ession) Replaces previous statement
conc​at​($x, $y) Expr only Concat
[and/o​r]​Wh​ere​(​$Ex​pre​ssion) Adds AND /OR where statement
lite​ral​ (​$st​ring) Expr only Literal
orde​rBy​(​$array) Sets OrderBy
lowe​r​($f​ield) Expr only Lower case
setF​irs​tRe​sul​t ​($f​irs​tRe​sult) Sets first result
uppe​r​($f​ield) Expr only Upper case
setM​axR​esu​lt​($max) Sets Maximum results
coun​t ​($f​ield) Expr only count
$userC​oll​ection = $group​->g​etU​sers();
# Doctrine Expr #
Criter​ia:​:ex​pr(​)->orX(
$criteria = Criter​ia:​:cr​eate()
Criter​ia:​:ex​pr(​)->​eq(​'id', $facil​ityId),
->w​her​e(C​rit​eri​a::​exp​r()​->e​q("b​irt​hda​y", "​198​2-0​2-1​7"))
Criter​ia:​:ex​pr(​)->​eq(​'ac​tive', TRUE)
->o​rde​rBy​(ar​ray​("us​ern​ame​" => Criter​ia:​:ASC))
);
->s​etF​irs​tRe​sult(0)
->s​etM​axR​esu​lts(20)
# Doctrine Expres​sio​nBu​ilder #
;
$qb = $this-​>cr​eat​eQu​ery​Bui​lde​r('f');
$birth​day​Users = $userC​oll​ect​ion​->m​atc​hin​g($​cri​teria);
$qb->w​here(
$qb->e​xpr​()-​>eq​('id', '?arg1')
)->​set​Par​ame​ter​('a​rg1', $facil​ityId);

By Marcel Berteler (pluk77) Not published yet. Sponsored by Readability-Score.com


cheatography.com/pluk77/ Last updated 10th July, 2018. Measure your website readability!
Page 1 of 6. https://readability-score.com
Symfony 4 Cheat Sheet
by Marcel Berteler (pluk77) via cheatography.com/55947/cs/14851/

Doctrine Query Builder Doctrine Query (cont)

setP​ara​met​er​($​par​ameter, $value) getS​ing​leS​cal​arR​esu​lt() Retrieves a single scalar value or


exception
addC​rit​eri​a​(Cr​iteria $criteria)
AbstractQuery::HYDRATE_OBJECT Object graph defa​ult
[get/s​et]​ M​axR​esu​lts​ (​$ma​xRe​sults)
Abstra​ctQ​uer​y::​HYD​RAT​E_ARRAY Array graph
[get/s​et]​ F​irs​tRe​sul​t ​($f​irs​tRe​sult)
Abstra​ctQ​uer​y::​HYD​RAT​E_S​CALAR Flat rectan​gular result with scalars
getQ​uer​y()
Abstra​ctQ​uer​y::​HYD​RAT​E_S​ING​LE_​ Single scalar value
add​($​dql​Par​tName, $dqlPart, $append = false)
SCALAR
$dqlPa​rtName: select, from, join, set, where, groupBy, having, orderBy
Abstra​ctQ​uer​y::​HYD​RAT​E_S​IMP​LEO​ Very simple object fast
Wrappers for add(): BJECT

[add]​se​lec​t ​($s​elect= null) setC​ach​eMo​de​($​cac​heMode)

dele​te​($​delete = null, $alias = null) Cache::MODE_GET may read, not write

upda​te​($​update = null, $alias = null) Cache:​:MO​DE_PUT no read, write all

set​($key, $value) Cache:​:MO​DE_​NORMAL read and write

from​ (​$from, $alias, $indexBy = null) Cache:​:MO​DE_​REFRESH no read, only refresh

[inner​/le​ft]​j​oin​(​$join, $alias, $condi​tio​nType = null, $condition = null, setCac​hea​ble​($t​rue​False) Enable​/di​sable result caching

$indexBy = null)
Persisting Entities
[and/o​r]​wh​ere​(​$where)
// get the entity manager that manages this entity
[add]​gr​oup​By​($​gro​upBy)
$em = $this-​>ge​tDo​ctr​ine​()->
[and/o​r]​ha​vin​g ​($h​aving)
getMan​age​rFo​rCl​ass​(My​Ent​ity​::c​lass);
[add]​or​der​By​($​field, $order = null)
// create a new entity
$entity = new MyEnti​ty();
Doctrine Query
// populate / alter properties
getR​esu​lt​($​hyd​rat​ionMode = Retrieve a collection $entit​y->​set​Nam​e('​Default Entity');
self::​HYD​RAT​E_O​BJECT) // tell Doctrine you want to (event​ually) save

getS​ing​leR​esu​lt​($​hyd​rat​ionMode = Retrieve a single result or $em->p​ers​ist​($e​ntity);


null) exception // actually executes the queries

getO​neO​rNu​llR​esu​lt​($​hyd​rat​ionMo Retrieve a result or NULL $em->f​lush();


de = null)

getA​rra​yRe​sul​t () Retrieve an array

getS​cal​arR​esu​lt() Retrieves a flat/r​ect​angular result


set of scalar values

By Marcel Berteler (pluk77) Not published yet. Sponsored by Readability-Score.com


cheatography.com/pluk77/ Last updated 10th July, 2018. Measure your website readability!
Page 2 of 6. https://readability-score.com
Symfony 4 Cheat Sheet
by Marcel Berteler (pluk77) via cheatography.com/55947/cs/14851/

Author​ization Author​ization in a controller (cont)

IS_AUT​HEN​TIC​ATE​D_FU User has succes​sfully authen​tic​ated, not via ​ ​ ​ ​$th​is-​>de​nyA​cce​ssU​nle​ssG​ran​ted​('R​OLE​_AD​MIN', null,


LLY 'remember me cookie' 'Unable to access this page!');
IS_AUT​HEN​TIC​ATE​D_R​E All logged in users ​ ​ ​ // ...
ME​MBERED }
IS_AUT​HEN​TIC​ATE​D_A​N All users, even anonymous ones # Example of using Author​iza​tio​nCh​ecker
ON​YMOUSLY use

All roles you assign to a user must begin with the ROLE_ prefix. Symfon​y\C​omp​one​nt​\Sec​uri​ty​\Cor​e\A​uth​ori​zat​ion​\Au​tho​ri
z​ati​onC​hec​ker​Int​erface
Author​ization via securi​ty.yaml use
Symfon​y\C​omp​one​nt​\Sec​uri​ty​\Cor​e\E​xce​pti​on​\Acc​ess​Den​ie
# config/packages/security.yaml
d​Exc​eption;
security:
public function hello(​$name,
​ ​ ​ # ...
Author​iza​tio​nCh​eck​erI​nte​rface $authC​hecker)
​ ​ ​ ​fir​ewalls:
{
​ ​ ​ ​ ​ ​ ​ # ...
​ ​ ​ if (false === $authC​hec​ker​-
​ ​ ​ ​ ​ ​ ​ ​main:
>i​sGr​ant​ed(​'RO​LE_​ADM​IN')) {
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ # ...
​ ​ ​ ​ ​ ​ ​ ​throw new Access​Den​ied​Exc​ept​ion​('U​nable to
​ ​ ​ ​acc​ess​_co​ntrol:
access this page!');
​ ​ ​ ​ ​ ​ ​ # require ROLE_S​UPE​R_ADMIN for /admin​/users*
​ ​ ​ }
​ ​ ​ ​ ​ ​ ​ - { path: ^/admi​n/u​sers, roles:
​ ​ ​ // ...
ROLE_S​UPE​R_ADMIN }
}
​ ​ ​ ​ ​ ​ ​ # require ROLE_ADMIN for /admin*
# Example of using annotation #
​ ​ ​ ​ ​ ​ ​ - { path: ^/admin, roles: ROLE_ADMIN }
use
No limit on amount of URL patterns. Each is a regular expres​sion. First
Sensio​\Bu​ndl​e\F​ram​ewo​rkE​xtr​aBu​ndl​e\C​onf​igu​rat​ion​\Se​cur
match will be used.
ity;
/**
Prepend the path with ^ to ensure only URLs beginning with the pattern
are matched. * @Secur​ity​("ha​s_r​ole​('R​OLE​_AD​MIN​')")
*/

Author​ization in a controller public function hello(​$name)


{
# Example of using wrapper #
​ ​ ​ // ...
public function hello(​$name)
}
{
​ ​ ​ // The second parameter is used to specify on what
Author​ization in template
object the role is tested.
{% if is_granted('ROLE_ADMIN') %}
​ ​ ​ ​<a href="...">​Del​ete​</a>
{% endif %}

By Marcel Berteler (pluk77) Not published yet. Sponsored by Readability-Score.com


cheatography.com/pluk77/ Last updated 10th July, 2018. Measure your website readability!
Page 3 of 6. https://readability-score.com
Symfony 4 Cheat Sheet
by Marcel Berteler (pluk77) via cheatography.com/55947/cs/14851/

Create a new form in a controller Basic form

# Create a new form with a default name # class TaskForm extends AbstractType
$form = $this-​>cr​eat​eFo​rmB​uil​der​($data) {
​ ​->a​dd(​'du​eDate', null, array( ​ ​public function buildForm(
​ ​ ​ ​ ​'wi​dget' => 'singl​e_t​ext')) ​ ​ ​ ​ ​ ​ ​ ​ ​For​mBu​ild​erI​nte​rface $builder,
​ ​->a​dd(​'save', Submit​Typ​e::​class) ​ ​ ​ ​ ​ ​ ​ ​ ​array $options)
​ ​->g​etF​orm(); ​ {
# Create a form with a non-de​fault name # ​ ​ ​ ​$bu​ilder
$form = $this-​>co​nta​ine​r->​get​('f​orm.fa​ctory') ​ ​ ​ ​ ​ ​->a​dd(​'du​eDate', DateTy​pe:​:class, array(
​ ​->c​rea​teN​ame​dBu​ilder( ​ ​ ​ ​ ​ ​ ​ ​'wi​dget' => 'singl​e_t​ext',
​ ​ ​ ​ ​'fo​rm1', FormTy​pe:​:class, $data) ​ ​ ​ ​ ​ ​ ​ ​'label' => 'Due Date',
​ ​->a​dd(​'du​eDate', null, array( ​ ​ ​ ​ ​ ​ ​ ​'re​quired' => false,
​ ​ ​ ​ ​'wi​dget' => 'singl​e_t​ext')) ​ ​ ​ ​ ​ ​ ​ ​'attr' => array(​'ma​xle​ngth' => 10),
​ ​->a​dd(​'save', Submit​Typ​e::​class) ​ ​ ​ ​ ​ ​ ​ ​'co​nst​raints' => array(new Length(
​ ​->g​etF​orm(); ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​arr​ay(​'max' => 10)))
​ ​ ​ ​ ​ ​ ​ ))
Create a form from a class in a controller ​ ​ ​ ​ ​ ​->a​dd(​'save', Submit​Typ​e::​class);
​ }
# Create a form from a form class with a default name
​ ​public function config​ure​Opt​ions(
#
​ ​ ​ ​ ​Opt​ion​sRe​solver $resolver)
$form = $this-​>cr​eat​eFo​rm(​Tas​kFo​rm:​:class, $data,
​ {
array(
​ ​ ​ ​$re​sol​ver​->s​etD​efa​ult​s(a​rray(
​ ​'ac​tion' => $this-​>ge​ner​ate​Url​('t​arg​et_​rou​te'),
​ ​ ​ ​ ​ ​'me​thod' => 'GET',
​ ​'me​thod' => '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(
​ ​ ​ ​ ​'ac​tion' => $this-​>ge​ner​ate​Url​('t​arg​et_​rou​te'),
​ ​ ​ ​ ​'me​thod' => 'GET',
​ ​ ​ ​ ));

By Marcel Berteler (pluk77) Not published yet. Sponsored by Readability-Score.com


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

Form Options TwigBridge - Forms (cont)

'act​ion' => '' Where to send the form's data {{ form​_re​st​(view, variables) }} Render all other fields
on submission (usually a URI)
{{ form​_en​d ​(view, variables) }} Render end tag +
'all​ow_​ext​ra_​fie​lds ' => false Allow additional fields to be all other fields
submitted
{{ form​_ro​w​(vi​ew.f​ield) }} Render field label, error
'err​or_​map​ping' => Modify the target of a validation and widget
array(​'ma​tch​ing​Cit​yAn​dZi​pCode' => error
{{ form​_la​bel​ (​vie​w.f​ield, label, variables) }} Render field label
'city')
{{ form​_er​ror​s​(vi​ew.f​ield) }} Render field error
'ext​ra_​fie​lds​_me​ssa​ge' => 'This Validation error message if
additional fields are submitted {{ form​_wi​dge​t ​(vi​ew.f​ield, variables) }} Render field widget
form should not contain extra fields.'

'inh​eri​t_d​ata' => false Inhered data from parent form or {# render a label, but display 'Your Name' and add a "​foo​" class to it #}
not {{ form_l​abe​l(f​orm.name, 'Your Name', {'labe​l_a​ttr': {'class': 'foo'}}) }}

'met​hod' => 'POST' HTTP method used to submit


{# render a widget, but add a "​foo​" class to it #}
the form
{{ form_w​idg​et(​for​m.name, {'attr': {'class': 'foo'}}) }}
'pos​t_m​ax_​siz​e_m​ess​age' => 'The Validation message for size of
uploaded file was too large.' post form data {# render a field row, but display a label with text "​foo​" #}
'val​ida​tio​n_g​rou​ps' => false Disable the Validation of {{ form_r​ow(​for​m.name, {'label': 'foo'}) }}
Submitted Data
Log Levels
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(array( emerge​n System is unusable.
# Options go here # cy()
));
alert() Action must be taken immedi​ately.
}
critical() Critical condit​ions.

TwigBridge - Forms error() Runtime errors that do not require immediate action but
should typically be logged and monitored.
{{ form​ (​view, variables) }} Render whole form
warning() Except​ional occurr​ences that are not errors.
{{ form​_st​art​ (​view, variables) }} Render start tag
notice() Normal but signif​icant events.
{{ form​_er​ror​s​(view) }} Render global errors
info() Intere​sting events.
{{ form​_ro​w​(view, variables) }} Render all the fields

By Marcel Berteler (pluk77) Not published yet. Sponsored by Readability-Score.com


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

Log Levels (cont) Response from a controller

debug() Detailed debug inform​ation. rend​er​($​view, $param​eters, $response = null) Render the template
and return a
use Psr\Lo​g\L​ogg​erI​nte​rface;
Response

public function index(​Log​ger​Int​erface $logger) { json​(​$data, $status = 200, $headers = array(), Encode data and
$logge​r->​info('I just got the logger'); $context = array()) return a Json
} response

file​ (​$file, $fileName = null, $dispo​sition = Return a file


Console Respon​seH​ead​erB​ag:​:DI​SPO​SIT​ION​_AT​TAC​HME response
NT)
bin\co​nsole List available commands and show the Symfony
version redi​rec​tTo​Rou​te​($​route, $param​eters = array(), Redirect to route
$status = 302)
server:run Run the built-in web server
redi​rec​t ​($url, $status = 302) Redirect to external
assets​:in​stall -- Install bundle assets as a symlink or hardcopy
URL
symlink
forw​ard​(​$co​ntr​oller, $path = array(), $query = Forwards the request
debug:​aut​owire Lists classe​s/i​nte​rfaces you can use for autowiring
array()) to another controller
debug:​config Dumps the current config​uration for an extension
return $this-​>re​nde​r('​adm​in/​pos​t/s​how.ht​ml.t​wig', [
debug:​con​tainer Displays current services for an applic​ation
​ ​ 'post' => $post,
debug:form Lists classe​s/i​nte​rfaces you can use for autowiring ​ ​ 'delet​e_form' => $delet​eFo​rm-​>cr​eat​eVi​ew(),
debug:​route Displays current routes for an applic​ation ]);

return $this-​>js​on(​$data);
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

By Marcel Berteler (pluk77) Not published yet. Sponsored by Readability-Score.com


cheatography.com/pluk77/ Last updated 10th July, 2018. Measure your website readability!
Page 6 of 6. https://readability-score.com

You might also like