Skip to content

Instantly share code, notes, and snippets.

@vikbert
Last active April 12, 2018 07:07
Show Gist options
  • Save vikbert/868bde8e1c8803f0a2e1616e6a4eabff to your computer and use it in GitHub Desktop.
Save vikbert/868bde8e1c8803f0a2e1616e6a4eabff to your computer and use it in GitHub Desktop.
[symfony] php snippets in symfony project #symfony, #php, #snippet

generate URLs from ROUTE

// annotation of route
/*
 * @Route("/checkout/address/edit/{id}", name="checkout_address_modify", requirement={"id": "\d+})
 */
public function editAction() {}

/*
 * @Route("/articles/{_locale}/{year}/{slug}.{_format}", name="article_show", 
 * requirements={
 *   "_locale": "de|en",
 *   "_format": "html|rss",
 *   "year": "\d+"
 * })
 */

generate URL in controller

public function showAction() {}
// twig: generate URL from route
<a href="{{ path('item_show', { 'seoContaminatedSku': item.seoContaminatedSku }) }}" > </a>
<a href="{{ path('watchlist_add', { 'id': item.getId(), 'returnPath': app.request.getRequestUri() | url_encode }) }}" >
  
// controller: /checkout/address/edit/{id}
$this->get('router')->generate('checkout_address_modify', ['id' => 123]);
## /checkout/address/edit/123

// controller: /checkout/address/edit/{id}
$this->get('router')->generate('checkout_address_modify', ['id' => 123, 'type'=> 'invoice']);
## /checkout/address/edit/123?type=invoice
## additional parameter will be used as query parameters

$this->get('router')->generate('checkout_address_modify', ['id' => 123], UrlGeneratorInterface::ABSOLUTE_URL);
## absolute URL: http://shop.local/checkout/address/edit/123

generate URL in javascript

// javascript: generate URL from route
<script>
  var route = "{{ path('blog_show', {'slug': 'my-blog-post'})|escape('js') }}";
  ## the escape() function helps escapes any non-javascript-safe values.
</script>

common used annotations

/**
 * @IsGranted("IS_AUTHENTICATED_FULLY")
 * @Security("is_granted('EDIT', post)")
 */
public function someAction(Post $post): Response { ... }

/**
 * @Cache(smaxage="300")
 */
public function someAction(Request $request): Response { ... }

/**
 * @expectedException FooException
 */
public function testThrowExceptionGivenACertainScenario()
{
    $this->doAction();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment