synfony-configuracao

Olá!

Este post é uma compilação de outros artigos, como este aqui e a documentação oficial do Sonata, que pode ser visualizada neste link.

Fizemos este post a fim de ajudar quem está engatinhando no Symfony2 e gostaria de um substituto para o GuardPlugin da versão 1.4.

Primeiramente, habilite as traduções padrão para os bundles, se desejar, no seu arquivo config (app/config/config.yml):pre lang=”yaml”>framework:
translator: ~

Em seguinda, altere o arquivo deps de sua aplicação e inclua os seguintes bundles:

[FOSUserBundle]
    git=git://github.com/FriendsOfSymfony/FOSUserBundle.git
    target=bundles/FOS/UserBundle
 
[SonataAdminBundle]
    git=git://github.com/sonata-project/SonataAdminBundle.git
    target=/bundles/Sonata/AdminBundle
    version=origin/2.0
 
[SonataBlockBundle]
    git=http://github.com/sonata-project/SonataBlockBundle.git
    target=/bundles/Sonata/BlockBundle
 
[SonataCacheBundle]
    git=http://github.com/sonata-project/SonataCacheBundle.git
    target=/bundles/Sonata/CacheBundle
 
[SonataDoctrineORMAdminBundle]
    git=http://github.com/sonata-project/SonataDoctrineORMAdminBundle.git
    target=/bundles/Sonata/DoctrineORMAdminBundle
 
[SonatajQueryBundle]
    git=http://github.com/sonata-project/SonatajQueryBundle.git
    target=/bundles/Sonata/jQueryBundle
 
[SonataUserBundle]
    git=git://github.com/sonata-project/SonataUserBundle.git
    target=/bundles/Sonata/UserBundle
 
[SonataEasyExtendsBundle]
    git=git://github.com/sonata-project/SonataEasyExtendsBundle.git
    target=/bundles/Sonata/EasyExtendsBundle
 
[gedmo-doctrine-extensions]
    git=git://github.com/l3pp4rd/DoctrineExtensions.git
 
[DoctrineExtensionsBundle]
    git=git://github.com/stof/StofDoctrineExtensionsBundle.git
    target=/bundles/Stof/DoctrineExtensionsBundle
 
[KnpMenuBundle]
    git=http://github.com/KnpLabs/KnpMenuBundle.git
    target=/bundles/Knp/Bundle/MenuBundle
 
[KnpMenu]
    git=http://github.com/KnpLabs/KnpMenu.git
    target=/knp/menu
 
[Exporter]
    git=http://github.com/sonata-project/exporter.git
    target=/exporter

Agora, vamos executar o script em vendors para fazermos o download dos bundles:

php bin/vendors install

Nosso próximo passo é fazer as seguintes alterações no autoload.php (app/autoload.php)…

$loader->registerNamespaces(array(
    // ...
    'Sonata'     => __DIR__.'/../vendor/bundles',
    'Exporter'   => __DIR__.'/../vendor/exporter/lib',
    'Knp\Bundle' => __DIR__.'/../vendor/bundles',
    'Knp\Menu'   => __DIR__.'/../vendor/KnpMenu/src',
    'FOS' => __DIR__.'/../vendor/bundles',
    // ...
));

… e no AppKernel (app/AppKernel.php):

public function registerBundles()
{
    return array(
        // ...
        new Sonata\AdminBundle\SonataAdminBundle(),
        new Sonata\BlockBundle\SonataBlockBundle(),
        new Sonata\CacheBundle\SonataCacheBundle(),
        new Sonata\jQueryBundle\SonatajQueryBundle(),
        new Knp\Bundle\MenuBundle\KnpMenuBundle(),
        new FOS\UserBundle\FOSUserBundle(),
        new Sonata\UserBundle\SonataUserBundle('FOSUserBundle'),
        new Application\Sonata\UserBundle\ApplicationSonataUserBundle(),
        new Sonata\EasyExtendsBundle\SonataEasyExtendsBundle(),
        new Sonata\DoctrineORMAdminBundle\SonataDoctrineORMAdminBundle(),
        new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
        // ...
    );
}

Adicione em seu config (app/config/config.yml):

fos_user:
    db_driver: orm
    firewall_name: main
    user_class: Application\Sonata\UserBundle\Entity\User

Vamos executar a seguinte linha de código:

php app/console sonata:easy-extends:generate SonataUserBundle

Adicione o bundle no AppKernel.php (app/AppKernel.php):

public function registerbundles()
    {
        $bundles = array(
            // Application Bundles
            // ...
            new Application\Sonata\UserBundle\ApplicationSonataUserBundle(),
            // ...
        );
        // ...
    }

Adicione ao routing.yml (app/config/routing.yml):

fos_user_security:
    resource: "@FOSUserBundle/Resources/config/routing/security.xml"

fos_user_profile:
    resource: "@FOSUserBundle/Resources/config/routing/profile.xml"
    prefix: /profile

fos_user_register:
    resource: "@FOSUserBundle/Resources/config/routing/registration.xml"
    prefix: /register

fos_user_resetting:
    resource: "@FOSUserBundle/Resources/config/routing/resetting.xml"
    prefix: /resetting

fos_user_change_password:
    resource: "@FOSUserBundle/Resources/config/routing/change_password.xml"
    prefix: /change-password

admin:
    resource: '@SonataAdminBundle/Resources/config/routing/sonata_admin.xml'
    prefix: /admin

_sonata_admin:
    resource: .
    type: sonata_admin
    prefix: /admin

soanata_user:
    resource: '@SonataUserBundle/Resources/config/routing/admin_security.xml'
    prefix: /admin

Adicione ao security.yml (app/config/security.yml):

security:
    encoders:
        FOS\UserBundle\Model\UserInterface: sha512

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_SONATA_ADMIN, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
        SONATA:
            - ROLE_SONATA_PAGE_ADMIN_PAGE_EDIT  # if you are not using acl then this line must be uncommented

    providers:
        fos_userbundle:
            id: fos_user.user_manager

    firewalls:

        # -> custom firewall for the admin area of the URL
        admin:
            pattern:      /admin(.*)
            form_login:
                provider:       fos_userbundle
                login_path:     /admin/login
                use_forward:    false
                check_path:     /admin/login_check
                failure_path:   null
            logout:
                path:           /admin/logout
            anonymous:    true
        # -> end custom configuration
 
        # defaut login area for standard users
        main:
            pattern:      .*
            form_login:
                provider:       fos_userbundle
                login_path:     /login
                use_forward:    false
                check_path:     /login_check
                failure_path:   null
            logout:       true
            anonymous:    true
 
# ...

    access_control:
        # URL of FOSUserBundle which need to be available to anonymous users
        - { path: ^/_wdt, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/_profiler, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
 
        # -> custom access control for the admin area of the URL
        - { path: ^/admin/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/logout$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/login-check$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        # -> end

        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
 
        # Secured part of the site
        # This config requires being logged for the whole site and having the admin role for the admin part.
        # Change these rules to adapt them to your needs
        - { path: ^/admin, role: [ROLE_ADMIN, ROLE_SONATA_ADMIN] }
        - { path: ^/.*, role: IS_AUTHENTICATED_ANONYMOUSLY }
# ...

Agora, atualize seu DB rodando o seguinte comando:

php app/console doctrine:schema:update force

E instale os assests dos bundles:

php app/console assets:install web

Limpe o cache:

php app/console cache:clear

Agora, você já pode criar o seu usuário através do comando:

php app/console fos:user:create

Pronto! Agora você pode acessar a área restrita do seu site através da url …/app_dev.php/admin/dashboard. No próximo post, vamos avaliar a criação de módulos para a área administrativa do nosso site.