Share
Embed
Как превратить проект на symfony в боль. Набор практических советов на основе реальных проектов
fwdays
October 18, 2013
Transcript
83 slides
-
Who is this guy? • Web developer since 2005 •
Evercode Lab – Co-founder and CEO • Using Symfony2 since 2011 • Love foosball and comics -
Why use frameworks? • Code Organization • Existing wheels •
Faster development • Community • Focus on your business logic, not core features -
Project Structure !"" app # !"" AppKernel.php # !"" cache
# !"" config # !"" logs | $"" ... !"" bin !"" composer.json !"" composer.lock !"" src # $"" Acme !"" vendor $"" web !"" app.php !"" app_dev.php $"" ... -
Project Structure !"" app # !"" autoload.php # !"" AppCache.php
# !"" AppKernel.php # !"" config # $"" Resources !"" bin # !"" console # $"" symfony_requirements !"" phpunit.xml.dist !"" src !"" var # !"" bootstrap.php.cache # !"" cache # !"" logs # $"" SymfonyRequirements.php $"" web -
Project Structure !"" SomeNamespace # !"" Bundles # !"" Themes
# $"" Utilities !"" CompanyName # !"" CampaignBundle # $"" RedactorBundle !"" Vagrant !"" build.xml !"" default.build.properties $"" symfony !"" app !"" composer.json !"" schema.xml $"" web -
Environments !"" app # !"" config # # !"" config.yml
# # !"" config_alex.yml # # !"" config_artur.yml # # !"" config_dev.yml # # !"" config_john.yml # # !"" config_prod.yml # # !"" config_test.yml # # !"" parameters.yml # # !"" ... $"" web !"" app.php !"" app_alex.php !"" app_artur.php !"" app_dev.php !"" app_john.php -
Environments • Environment is not each machine you running your
project on • Environment is each project configuration you use -
Environments • You should be able to run your app
using each environment on your local machine • So, please, be nice and keep env’s configs in sync • And put sensitive params to parameters.yml or ignored local config -
Coupling app to env namespace App\MainBundle\Service; class Mailer { private
$env public function __construct($env) { $this->env = $env; } public function mail($to, $subject, $body) { if($this->env != 'prod') { return; } // ... } } -
Decoupling app from env namespace App\MainBundle\Service; class Mailer { private
$disableDelivery public function __construct($disableDelivery) { $this->disableDelivery = $disableDelivery; } public function mail($to, $subject, $body) { if($this->disableDelivery) { return; } // ... } } -
The application should not be aware of what environment it
is running under, it should just be configured a particular way based on its configuration files. http://richardmiller.co.uk/2013/05/28/symfony2-avoiding-coupling-applications-to-the-environment/ http://www.flickr.com/photos/ezu/73784031/ -
Cache and logs /** * change caching directory for the
system's - * optimization for local/test/dev * * @return string */ public function getCacheDir() { if (in_array( $this->environment, array('dev','test','local')) ) { return sys_get_temp_dir() . '/cache/' . $this->environment; } return parent::getCacheDir(); } -
Cache and logs /** * change caching directory for the
system's - * optimization for local/test/dev * * @return string */ public function getCacheDir() { if (in_array( $this->environment, array('dev','test','local')) ) { return sys_get_temp_dir() . '/cache/' . $this->environment; } return parent::getCacheDir(); } -
Cache and logs How many times you just set umask(0000)?
http://symfony.com/doc/current/book/ installation.html#configuration-and-setup -
Annoying Composer? • Add your composer.lock to .gitignore • ...
• Profit! • Wait, no. Have fun, bitches! -
Let’s change vendors! Edit vendor/sonata-project/user-bundle/Sonata/UserBundle/ Model/User.php. Change line: use FOS\UserBundle\Entity\User
as AbstractedUser; to use FOS\UserBundle\Document\User as AbstractedUser; -
The vendor directory is a black box. The public API
is vendor/autoload.php. https://igor.io/2013/09/04/composer-vendor-directory.html http://www.flickr.com/photos/ezu/73784031/ -
The upside of OSS is that you are in charge,
and you actually can fix things when they break. Also, you can prevent them from breaking in the first place. https://igor.io/2013/09/24/dependency-responsibility.html http://www.flickr.com/photos/ezu/73784031/ -
.gitignore *.iml *.DS_Store .idea Acme/DemoBundle/AcmeDemoBundle.php Acme/DemoBundle/Controller/DemoController.php Acme/DemoBundle/Controller/SecuredController.php Acme/DemoBundle/Controller/WelcomeController.php Acme/DemoBundle/DependencyInjection/AcmeDemoExtension.php Acme/DemoBundle/EventListener/ControllerListener.php
Acme/DemoBundle/Form/ContactType.php Acme/DemoBundle/Resources/config/services.xml Acme/DemoBundle/Resources/public/css/demo.css Acme/DemoBundle/Resources/public/images/blue-arrow.png Acme/DemoBundle/Resources/public/images/field-background.gif Acme/DemoBundle/Resources/public/images/logo.gif Acme/DemoBundle/Resources/public/images/search.png Acme/DemoBundle/Twig/Extension/DemoExtension.php ... -
Wut .gitignore?! • vendors • compiled assets • Acme •
parameters.yml • composer.lock -
Classic class SomeExtension extends \Twig_Extension { ... $cluster = $this->container
->get('some.manager') ->getCurrentSomething(); ... } -
Extended class RubricService { public function __construct($security, ...) { $this->user
= $security->getToken()->getUser(); ... } } -
ACL • Don’t use ACL • Common, just never don’t
• Even if somebody asks you to -
ACL • Don’t use ACL • Common, just never don’t
• Even if somebody asks you to • Just. Don’t. Use. ACL -
ACL • Don’t use ACL • Common, just never don’t
• Even if somebody asks you to • Just. Don’t. Use. ACL • Another bullet about not using ACL -
Voters • Can user edit the record? • Is he
the author of it? • Does he have Roles:ROLE_SUPER_ADMIN ? • No? Then screw you! Access denied! -
Voters public function editAction($shopId) { $shop = // get the
Shop entity ... if (!$this->sc->isGranted("EDIT", $shop)) { throw new AccessDeniedExceptions); } } -
Voters use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; class ShopVoter implements VoterInterface {
public function supportsAttribute($attribute) { return in_array($attribute, array( "EDIT", "MANAGE_ADMINS", "DELETE") ); } public function supportsClass($class) { return $class == "App\AppBundle\Entity\Shop"; } } -
Voters public function vote(TokenInterface $token, $object, array $attributes) { if
(!$this->supportObject($object)) { return VoterInterface::ACCESS_ABSTAIN; } $accessToken = $this->container->get('request')->getUser(); try { $user = $this->getRepository('AppBundle:User') ->findUserByAccessToken($accessToken); if (!$user->getToken()->isActive()) { return VoterInterface::ACCESS_DENIED; } } catch (\Doctrine\ORM\NoResultException $e) { return VoterInterface::ACCESS_DENIED; } ... } -
Voters public function vote(TokenInterface $token, $object, array $attributes) { ...
if ($user->hasRole(UserRole::ROLE_ADMIN)) { return VoterInterface::ACCESS_GRANTED; } if ($object->getAdmins()->contains($user)) { return VoterInterface::ACCESS_GRANTED; } return VoterInterface::ACCESS_DENIED; } -
Naming <?php namespace Sto\ContentBundle\Form; class CompanyType extends AbstractType { ...
} <?php namespace Sto\AdminBundle\Form; class CompanyType extends AbstractType { ... } -
Naming • instead of NewUserEventListener use SendConfirmationListener • {name of
the bundle without “Bundle”}. {name of the controller without “Controller”}.{name of the action without “Action”} • Stay consistent -
Code generation inside generate generate:bundle Generates a bundle generate:controller Generates
a controller generate:doctrine:crud Generates a CRUD based on a ... generate:doctrine:entities Generates entity classes and ... generate:doctrine:entity Generates a new Doctrine ... generate:doctrine:form -
No $request->get() public function get($key, $default = null, $deep =
false) { return $this->query->get( $key, $this->attributes->get( $key, $this->request->get( $key, $default, $deep) , $deep) , $deep ); } -
You probably heard • Fat controllers • Tight coupling •
Code immobility -
Controller on a diet • get Request • init service
• call service’s method with params • return rendered Response