php

Tutorial Symfony – Redirecting

Il redirectig ci permette di reindirizzare il browser verso una nuova pagina.

In PHP classico utilizziamo:


// redirect verso pagina interna
header("location: /nuova-pagina.php");
exit; // serve per interrompere lo script dopo il cambio di pagina o PHP darà ERRORE

// redirect verso una risorsa esterna al sito
header("location: http://www.sito.it/pagina.php");
exit;

In Symfony utilizzeremo invece:


public function indexAction()
{
    // la funzione fa qualcosa

    // redirect externally
    return $this->redirect('http://symfony.com/doc');

    // la parte qui sotto non verrà eseguita perchè ho fatto return
}

In symfony invocheremo i metodi:

redirect(): per i link esterni
redirectToRoute(): per le pagine interne definite da @Route


public function indexAction()
{
    // redirect to the "homepage" route
    return $this->redirectToRoute('homepage');

    // do a permanent - 301 redirect - Moved Permanently
    // consente di spostare un dominio o una pagina ad un altro indirizzo 
    // senza perdere il potere e il posizionamento acquisito dalla vecchia pagina.
    return $this->redirectToRoute('homepage', array(), 301);

    // redirect to a route with parameters
    return $this->redirectToRoute('blog_show', array('slug' => 'my-page'));

    // redirect externally
    return $this->redirect('http://symfony.com/doc');
}

Bibliografia:
symfony.com/doc/current/controller.html

By |PHP, Symfony, Web Design|Commenti disabilitati su Tutorial Symfony – Redirecting

Symfony for Beginners – Send var to Template

How to passing data from a page to a .twig Template

1. Create in src\AppBundle\Controller\LuckyController.php


<?php
// src/AppBundle/Controller/LuckyController.php
namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller; // to extend Controller

class LuckyController extends Controller // extends Controllers of Symfony
{
    /**
     * @Route("/lucky/number")
     */
    public function numberAction() // my function
    {
        $number = mt_rand(0, 100); // random PHP function
        
        // send the variable to a .twig template
        return $this->render('lucky/number.html.twig', array(
            'number' => $number,
        ));
    }
}

2. Create in app\Resources\views\lucky\number.html.twig


{# app/Resources/views/lucky/number.html.twig #}

<h1>Your lucky number is {{ number }}</h1>

NOTICE:

a. The namespace to exted standard Controller of Symfony:
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

b. The class have to extend the Controller namespace:
class LuckyController extends Controller

c. render using lucky/number.html.twig the array key ‘number’ with value $number
return $this->render(‘lucky/number.html.twig’, array(
‘number’ => $number,

d. the template receive the value of number

<h1>Your lucky number is {{ number }}</h1>

{{ number }} -> this is the syntax of .twig to get the value sent by public function numberAction()

{# app/Resources/views/lucky/number.html.twig #} -> this is a comment only in .twig syntax

By |PHP, Symfony, Web Design|Commenti disabilitati su Symfony for Beginners – Send var to Template

Symfony for Beginners – RNG Generator

Open NetBeans, on the left column> LMB over src\AppBundle\Controller folder> New PHP Class> LuckyController

LuckyController.php


<?php
// src/AppBundle/Controller/LuckyController.php
namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;

class LuckyController
{
    /**
     * @Route("/lucky/number")
     */
    public function numberAction()
    {
        $number = mt_rand(0, 100); // this is plain PHP

        return new Response(
            '<html><body>Lucky number: '.$number.'</body></html>'
        );
    }
}

Go to: http://localhost/symfonytest/first_test_symfony/web/lucky/number

It will render – Lucky number: 87 –

You CAN NOT CHANGE:
– namespace use
– class name LuckyController

You CAN CHANGE
– @Route(“/lucky/number”)
– your public function

You HAVE TO:
– return new Response

Example:


<?php
// src/AppBundle/Controller/LuckyController.php
namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;

class LuckyController
{
    /**
     * @Route("/lucky")
     */
    public function myAction()
    {
        $numberOne = mt_rand(0, 100); // this is plain PHP
        $numberTwo = mt_rand(0, 100); // this is plain PHP

        return new Response(
            '<html><body>First number: '.$numberOne.' Second number: '. $numberTwo .'</body></html>'
        );
    }
}

Go to: http://localhost/symfonytest/first_test_symfony/web/lucky

First number: 84 Second number: 79

By |PHP, Symfony, Web Design|Commenti disabilitati su Symfony for Beginners – RNG Generator

Create your First Page in Symfony – Route and Controller

We need a code editor, for PHP you can use NetBeans (https://netbeans.org/features/php/) or PHP Storm (https://www.jetbrains.com/phpstorm/)

Inside the project folder there are some directory:
– app
– bin
– src
– tests
– var
– vendor
– web
– composer.json
– LICENSE etc…

Focus on:

A. src: it holds all PHP files (classes)

B. app: it holds configuration, templates

Let’s move on!

1. Go to src/AppBundle/Controller/DefaultController.php, this in the default welcome page, delete it.
Now we have a real empty project :)

2. We need to create a ‘route’ and a ‘controller’
The route is where is the page, its url in poor words.
The controller is a software program that manages or directs the flow of data between two entities, it is the function that build the page.

3. Create inside AppBundle\Controller\GenusController.php

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;  // namespace for route
use Symfony\Component\HttpFoundation\Response;               // namespace for http render

class GenusController 
{
	/**
	* @Route("/genus")
	*/
	public function showAction() // this is the controller that create the page, returns a Response Object
	{
		return new Response('Under the <strong>Sea!</strong>'); // HTTP Text Render
	}
	
}


NOTICE:

– namespace AppBundle\Controller … use etc…: a Symfony namespace necessary for development

– class GenusController: the name of php file GenusController.php
We have created a class named GenusController that can be find by Symfony at src\AppBundle\Controller

– We use this particular syntax to define the http route of the page

/**
* @Route(“/genus”)
*/

It will be http://localhost/symfonytest/first_test_symfony/web/genus

– Controller to create the page:


	public function showAction() // this is the controller that create the page, returns a Response Object
	{
		return new Response('Under the <strong>Sea!</strong>'); // HTTP Text Render
	}
	

Run from the browser: http://localhost/symfonytest/first_test_symfony/web/genus

Official Link:
Ref: http://knpuniversity.com/screencast/symfony/first-page

By |PHP, Symfony, Web Design|Commenti disabilitati su Create your First Page in Symfony – Route and Controller

Symfony for Beginners – Home Pages and .twig Templates – Dev Setup

Create your First Home Page in Symfony

Environment Setup – Automatic Clear Cache

At the end of installation process will have: C:\wamp64\www\symfonytest>cd first_test_symfony

Inside the folder will be the folder structure of my project:
– app
– bin
– src
– tests
– var
– vendor
– web
– composer.json
– LICENSE etc…

Open your broser at: http://localhost/symfonytest/first_test_symfony/web/ to see the welcome page

Go to web\app.php and change the line:

$kernel = new AppKernel(‘prod’, false);

to

$kernel = new AppKernel(‘prod’, true);

This will activate – (‘prod’, true) – the production environment, this mean cache will not be saved, you can change file and reload in browser on the fly and see changes.

If – (‘prod’, false) – you can not reload from browser code changes

Go to var\cache\dev and var\cache\prod to see cache files for ‘dev’ and ‘prod’ environment.

Net Beans IDE

1. Run Net Beans IDE

2. File> New Project> PHP> PHp Application with Existing Sources> NEXT> Browse: C:\wamp64\www\symfonytest>first_test_symfony

HTML Render

1. Controller Request

Go to src\AppBundle\Controller\ -> here you will find all php codes for controllers
Open src\AppBundle\Controller\DeafaultController.php
Change the render page to indexmy.html.twig


return $this->render('default/indexmy.html.twig ...

2. .twig.html

Go to app\Resources\views\default\
and create indexmy.html.twig


{% extends 'base.html.twig' %}

{% block body %}
<h1>This is my first home page</h1>
{% endblock %}

{% block stylesheets %}
<style>
    h1 { font-size: 36px; }
</style>
{% endblock %}

Notice that {% extends ‘base.html.twig’ %}

Go to app\Resources\views\base.html.twig


<!DOCTYPE html>

<html>
    
<head>
<meta charset="UTF-8" />
        
<title> {% block title %}Welcome{% endblock %}</title>
        
	{% block stylesheets %}{% endblock %}
        
<link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}" />
    
</head>
    
<body>
        
	{% block body %}{% endblock %}
        
	{% block javascripts %}{% endblock %}
    
</body>

</html>

The process is:

return $this->render(‘default/indexmy.html.twig: -> call html.twig template -> extend base.html.twig

The rendered code inside the browser will be:


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"><meta charset="UTF-8">
    <title>Welcome!</title>
	<style>
		h1 { font-size: 36px; }
	</style>
    <link rel="icon" type="image/x-icon" href="http://localhost/symfonytest/first_test_symfony/web/favicon.ico">
</head>
<body>
    <h1>This is my first home page</h1>
</body>
</html>

We can write:


{% extends 'base.html.twig' %}

{% block body %}
<h1>This is my first home page</h1>
<strong>Test</strong> HTML tags
<br>
<a href="http://www.lucedigitale.com">Visit Luce Digitale</a>
<br>
{% include 'my_code.html.twig' %}

{% endblock %}

{% block stylesheets %}
<style>
    h1 { font-size: 36px; }
</style>
{% endblock %}

Notice:
{% include ‘my_code.html.twig’ %} -> include a HTML code from a file in app\Resources\views\my_code.html.twig

Warning: you can not write native php code inside a .twig template, you need create an Extension Class (official docs at: http://symfony.com/doc/current/templating/twig_extension.html)

By |PHP, Symfony, Web Design|Commenti disabilitati su Symfony for Beginners – Home Pages and .twig Templates – Dev Setup