symfony2 interview questions
Top symfony2 frequently asked interview questions
Anyone knows how to concatenate strings in twig? I want to do something like:
{{ concat('http://', app.request.host) }}
Source: (StackOverflow)
I'm aware of questions like this, where people tend to discuss the general Symfony 2 concept of bundle.
The thing is, in a specific application, like, for instance, a twitter-like application, should everything really be inside a generic bundle, like the official docs say?
The reason I'm asking this is because when we develop applications, in general, we don't want to highly couple our code to some full-stack glue framework.
If I develop a Symfony 2 based application and, at some point, I decide Symfony 2 is not really the best choice to keep the development going, will that be a problem for me?
So the general question is: why is everything being a bundle a good thing?
EDIT#1
Almost a year now since I asked this question I wrote an article to share my knowledge on this topic.
Source: (StackOverflow)
When i am using this function
$ens = $em->getRepository('AcmeBinBundle:Marks')->findBy(array('type'=> 'C12'));
But i want the results in asceding order
Source: (StackOverflow)
I just created a new Symfony 2.5 project with a regular composer command:
php composer.phar create-project symfony/framework-standard-edition path/ 2.5.0
The Terminal asks me:
Would you like to use Symfony 3 directory structure?
What is this Symfony 3 directory structure?
I have never seen it before... Is it new since 2.5?
What are the benefits to using it?
Is there any way to replicate this directory structure?
Source: (StackOverflow)
I have a multidimensional array where some objects exist and others don't. I keep getting a
Method "code" for object "stdClass" does not exist in...?
The code I am using in my template is:
{% for item in items %}
<p>{% if item.product.code %}{{ item.product.code }}{% endif %}</p>
{% endfor %}
Some products do not have this code and unfortunately this data structure is provided via a feed, so I cannot change it.
When I looked at the Twig documentation I interpreted that if an object or method was not there it would just return null?
Source: (StackOverflow)
I have added a setting to my config.yml file as such:
app.config:
contact_email: somebody@gmail.com
...
For the life of me, I can't figure out how to read it into a variable. I tried something like this in one of my controllers:
$recipient =
$this->container->getParameter('contact_email');
But I get an error saying:
The parameter "contact_email" must be
defined.
I've cleared my cache, I also looked everywhere on the Symfony2 reloaded site documentation, but I can't find out how to do this.
Probably just too tired to figure this out now. Can anyone help with this?
Source: (StackOverflow)
I'm trying to use http caching. In my controller I'm setting a response as follows:
$response->setPublic();
$response->setMaxAge(120);
$response->setSharedMaxAge(120);
$response->setLastModified($lastModifiedAt);
dev mode
In dev environment first response is a 200 with following headers:
cache-control:max-age=120, public, s-maxage=120
last-modified:Wed, 29 Feb 2012 19:00:00 GMT
For next 2 minutes every response is a 304 with following headers:
cache-control:max-age=120, public, s-maxage=120
This is basically what I expect it to be.
prod mode
In prod mode response headers are different. Note that in app.php I wrap the kernel in AppCache.
First response is a 200 with following headers:
cache-control:must-revalidate, no-cache, private
last-modified:Thu, 01 Mar 2012 11:17:35 GMT
So it's a private no-cache response.
Every next request is pretty much what I'd expect it to be; a 304 with following headers:
cache-control:max-age=120, public, s-maxage=120
Should I worry about it? Is it an expected behaviour?
What will happen if I put Varnish or Akamai server in front of it?
I did a bit of debugging and I figured that response is private because of last-modified header. HttpCache kernel uses EsiResponseCacheStrategy to update the cached response (HttpCache::handle() method).
if (HttpKernelInterface::MASTER_REQUEST === $type) {
$this->esiCacheStrategy->update($response);
}
EsiResponseCacheStrategy turns a response into non cacheable if it uses either Last-Response or ETag (EsiResponseCacheStrategy::add() method):
if ($response->isValidateable()) {
$this->cacheable = false;
} else {
// ...
}
Response::isValidateable() returns true if Last-Response or ETag header is present.
It results in overwriting the Cache-Control header (EsiResponseCacheStrategy::update() method):
if (!$this->cacheable) {
$response->headers->set('Cache-Control', 'no-cache, must-revalidate');
return;
}
I asked this question on Symfony2 user group but I didn't get an answer so far: https://groups.google.com/d/topic/symfony2/6lpln11POq8/discussion
Update.
Since I no longer have access to the original code I tried to reproduce the scenario with the latest Symfony standard edition.
Response headers are more consistent now, but still seem to be wrong.
As soon as I set a Last-Modified
header on the response, the first response made by a browser has a:
Cache-Control:must-revalidate, no-cache, private
Second response has an expected:
Cache-Control:max-age=120, public, s-maxage=120
If I avoid sending If-Modified-Since
header, every request returns must-revalidate, no-cache, private
.
It doesn't matter if the request was made in prod
or dev
environment anymore.
Source: (StackOverflow)
How do I get the current route in Symfony 2?
For example, routing.yml
:
somePage:
pattern: /page/
defaults: { _controller: "AcmeBundle:Test:index" }
How can I get this somePage
value?
Source: (StackOverflow)
I'm trying to make a simple example in order to learn how to delete a row from a parent table and automatically delete the matching rows in the child table using Doctrine2.
Here are the two entities I'm using:
Child.php:
<?php
namespace Acme\CascadeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="child")
*/
class Child {
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="Father", cascade={"remove"})
*
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="father_id", referencedColumnName="id")
* })
*
* @var father
*/
private $father;
}
Father.php
<?php
namespace Acme\CascadeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="father")
*/
class Father
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
}
The tables are correctly created on the database, but the On Delete Cascade option it's not created. What am I doing wrong?
Source: (StackOverflow)
I'm using Doctrine's QueryBuilder to build a query, and I want to get the total count of results from the query.
$repository = $em->getRepository('FooBundle:Foo');
$qb = $repository->createQueryBuilder('n')
->where('n.bar = :bar')
->setParameter('bar', $bar);
$query = $qb->getQuery();
//this doesn't work
$totalrows = $query->getResult()->count();
I just want to run a count on this query to get the total rows, but not return the actual results. (After this count query, I'm going to further modify the query with maxResults for pagination.)
Source: (StackOverflow)
I have a Symfony2 Twig template. I want to output the value of a config parameter in this twig template (a version number). Therefore I defined the config parameter like this:
parameters:
app.version: 0.1.0
I'm able to use this config parameter in Controllers but I have no clue how to get it in my Twig template.
Source: (StackOverflow)
In a Symfony2 app's routing configuration, I can refer to a file like this:
somepage:
prefix: someprefix
resource: "@SomeBundle/Resources/config/config.yml"
Is there any way to access a file relative to the bundle within a controller or other PHP code? In particular, I'm trying to use a Symfony\Component\Yaml\Parser object to parse a file, and I don't want to refer to that file absolutely. Essentially, I want to do this:
$parser = new Parser();
$config = $parser->parse( file_get_contents("@SomeBundle/Resources/config/config.yml") );
I've checked out the Symfony\Component\Finder\Finder class, but I don't think that's what I'm looking for. Any ideas? Or maybe I'm completely overlooking a better way of doing this?
Source: (StackOverflow)
I'm developing game app and using Symfony 2.0. I have many AJAX requests to the backend. And more responses is converting entity to JSON. For example:
class DefaultController extends Controller
{
public function launchAction()
{
$user = $this->getDoctrine()
->getRepository('UserBundle:User')
->find($id);
// encode user to json format
$userDataAsJson = $this->encodeUserDataToJson($user);
return array(
'userDataAsJson' => $userDataAsJson
);
}
private function encodeUserDataToJson(User $user)
{
$userData = array(
'id' => $user->getId(),
'profile' => array(
'nickname' => $user->getProfile()->getNickname()
)
);
$jsonEncoder = new JsonEncoder();
return $jsonEncoder->encode($userData, $format = 'json');
}
}
And all my controllers do the same thing: get an entity and encode some of its fields to JSON. I know that I can use normalizers and encode all entitities. But what if an entity has cycled links to other entity? Or the entities graph is very big? Do you have any suggestions?
I think about some encoding schema for entities... or using NormalizableInterface
to avoid cycling..,
Source: (StackOverflow)