Listen to Fabien potencier and talk about symfony2: What is symfony2?

Source: Internet
Author: User


What is symfoy2?

Why is another popular web MVC Framework in the PHP world? Fabien potencier doesn't say that!

Fabien potencier defines what symfoy2 is like:

First, symfony2 is an independent, loose, and tightly organized php component set. It can solve some general problems encountered in Web development.

Based on these components, symfoy2 can also be used as an independent web framework.

Is symfony2 a MVC framework?

Fabien potencier said symfony2 never defined itself as an MVC Framework!

So what is it? Fabien potencier: We never care about the MVC mode, but only care about the separation of concerns (separation of concerns ).

However, symfony2 provides partial implementation of the MVC mode: for example, the Controller part, but the view part does not have the mode part. However, you can implement it through the tightly inherited ORM (doctrine2 and propel.

 

From this perspective, symfony has not escaped from the Web MVC framework !!!

Fabien potencier said that symfony2 never wanted to rely on these ORM to make itself a follower of another MVC. Our goal is even greater!

 

Tell you, symfony2 is an HTTP framework or a request/response framework. We are focusing on the HTTP protocol instead of the MVC model. We are a lower-level and more basic framework.

Why should we say that? Yes!

With the development of Web in recent years, sometimes you only need to create a set of rest APIs, all the logic is put on the browser side, and the server side only provides data as a web. Believe it or not, check backbone. JS!

Besides, the MVC mode is only one of the implementation methods of Web applications.

Peel off all framework pattern skins. Do you see that the web program does not process a received request and then returns a response?

What we grasp in symfony2 is the root of the web program! Which of our many HTTP streaming media choose to use MVC?

In short, symfony2 is closer to the root layer than MVC. We are more basic and more common !!!

 

Speaking of symfony2, Fabien potencier said that we have more ambitious goals. How can we explain this?

Symfony2 will continue to focus on Pack technology research and innovation! We believe that she will continue to push forward the development of the web.

Let's take a look at the innovations we have included in symfony2!

From bundles, HTTP cache, distributed, dependency injection, template engine, declarative configuration, asset management, stable APIs to Web analyzer and other technologies have played a huge role in promoting the development of Web.

 

"You need to know that an independent framework will never be a standard in the PHP world, so symfony2 is exploring another way !"

"Sharing is everywhere ."

"We cannot duplicate wheel manufacturing ."

Therefore, we have closely integrated monolog, composer, doctrine, propel, assetic, twig, swiftmailer and other great products.

More importantly, we want to share our work with you!

Therefore, we finally chose the component path!

We will provide construction modules for all web projects, whether personal or commercial projects, or open-source projects!

 

It is said that the symfony2 code may contain classes or methods marked as @ API, which means that a method will not change from name to parameter and return value because of the development of symfony2, so if

If your project only uses this, you don't have to worry about the upgrade of symfony2.

 

Let's take a look at the current components of symfony2:

Dependencyinjection
Eventdispatcher
Httpfoundation
Domcrawler
Classloader
Cssselector
Httpkernel
Browserkit
Templating
Translation
Serializer
Validator
Security
Routing
Console
Process
Config
Finder
Locale
Yaml
Form

Fabien briefly introduces several Bundle:

1. classloader:

Implements an automatic loader based on the PSR-O standard (automatically loaded classes with namespaces, applicable to php5.3 and above), and can also load classes according to the pear naming rules. It is flexible to query classes to be loaded in different directories based on sub-namespaces. You can even specify multiple directories for a namespace.

 

require_once __DIR__.‘/src/Symfony/Component/ClassLoader/UniversalClassLoader.php‘; use Symfony\Component\ClassLoader\UniversalClassLoader; $loader = new UniversalClassLoader();$loader->registerNamespaces(array(    ‘Symfony‘          => array(__DIR__.‘/src‘, __DIR__.‘/symfony/src‘),    ‘Doctrine\\Common‘ => __DIR__.‘/vendor/doctrine-common/lib‘,    ‘Doctrine\\DBAL‘   => __DIR__.‘/vendor/doctrine-dbal/lib‘,    ‘Doctrine‘         => __DIR__.‘/vendor/doctrine/lib‘,    ‘Monolog‘          => __DIR__.‘/vendor/monolog/src‘,));$loader->registerPrefixes(array(    ‘Twig_‘ => __DIR__.‘/vendor/twig/lib‘,));$loader->register(); 

If you want to achieve higher execution efficiency, you can use the APC cached universal class loader.

 

2. console command line tool

It is convenient to use the command line tool when creating a web application. you can create your own command line tool like the following code:

 

use Symfony\Component\Console\Application;use Symfony\Component\Console\Input\InputInterface;use Symfony\Component\Console\Input\InputArgument;use Symfony\Component\Console\Input\InputOption;use Symfony\Component\Console\Output\OutputInterface; $console = new Application();$console    ->register(‘ls‘)    ->setDefinition(array(        new InputArgument(‘dir‘, InputArgument::REQUIRED, ‘Directory name‘),    ))    ->setDescription(‘Displays the files in the given directory‘)    ->setCode(function (InputInterface $input, OutputInterface $output) {        $dir = $input->getArgument(‘dir‘);         $output->writeln(sprintf(‘Dir listing for <info>%s</info>‘, $dir));    });$console->run();

 

3. yaml is a popular configuration format.

 

use Symfony\Component\Yaml\Yaml; $array = Yaml::parse($file); print Yaml::dump($array); 

 

4. Operations interface for finder excellent file resources.

use Symfony\Component\Finder\Finder; $finder = new Finder(); $iterator = $finder  ->files()  ->name(‘*.php‘)  ->depth(0)  ->size(‘>= 1K‘)  ->in(__DIR__); foreach ($iterator as $file) {    print $file->getRealpath()."\n";}

You can even use it to obtain resources in the Remote Server File System, such as files on Amazon S3:

$s3 = new \Zend_Service_Amazon_S3($key, $secret);$s3->registerStreamWrapper("s3"); $finder = new Finder();$finder->name(‘photos*‘)->size(‘< 100K‘)->date(‘since 1 hour ago‘);foreach ($finder->in(‘s3://bucket-name‘) as $file) {    print $file->getFilename()."\n";}

 

5. process component, which can be used to execute commands in an external process! The following example shows how to execute a simple directory LIST command and return the result:

use Symfony\Component\Process\Process; $process = new Process(‘ls -lsa‘);$process->setTimeout(3600);$process->run();if (!$process->isSuccessful()) {    throw new RuntimeException($process->getErrorOutput());} print $process->getOutput();

If you want to monitor the execution process, you can pass an anonymous method to the run method:

use Symfony\Component\Process\Process; $process = new Process(‘ls -lsa‘);$process->run(function ($type, $buffer) {    if (‘err‘ === $type) {        echo ‘ERR > ‘.$buffer;    } else {        echo ‘OUT > ‘.$buffer;    }});

 

6. php version of domcrawler jquery! You can use it to navigate to the HTML Dom structure or XML document.

use Symfony\Component\DomCrawler\Crawler; $crawler = new Crawler();$crawler->addContent(‘

 

7. CSS selector we often use XPath to access the DOM structure. In fact, it is easier to use CSS selector. This component is equivalent to converting CSS selector into XPath.

use Symfony\Component\CssSelector\CssSelector; print CssSelector::toXPath(‘div.item > h4 > a‘); 

Therefore, you can use cssselector and domcrawler to replace XPath:

use Symfony\Component\DomCrawler\Crawler; $crawler = new Crawler();$crawler->addContent(‘

 

8. httpfoundation

This component only adds an object-oriented layer to PHP-related web content, including request, response, uploaded files, cookies, sessions...

use Symfony\Component\HttpFoundation\Request;use Symfony\Component\HttpFoundation\Response; $request = Request::createFromGlobals();echo $request->getPathInfo();

You can use it to easily create your own request and response:

$request = Request::create(‘/?foo=bar‘, ‘GET‘);echo $request->getPathInfo();$response = new Response(‘Not Found‘, 404, array(‘Content-Type‘ => ‘text/plain‘));$response->send();

 

9. Routing

The routing component and request object work together to convert requests to response.

use Symfony\Component\HttpFoundation\Request;use Symfony\Component\Routing\Matcher\UrlMatcher;use Symfony\Component\Routing\RequestContext;use Symfony\Component\Routing\RouteCollection;use Symfony\Component\Routing\Route; $routes = new RouteCollection();$routes->add(‘hello‘, new Route(‘/hello‘, array(‘controller‘ => ‘foo‘))); $context = new RequestContext(); // this is optional and can be done without a Request instance$context->fromRequest(Request::createFromGlobals()); $matcher = new UrlMatcher($routes, $context); $parameters = $matcher->match(‘/hello‘);

 

10. eventdispatcher

use Symfony\Component\EventDispatcher\EventDispatcher;use Symfony\Component\EventDispatcher\Event; $dispatcher = new EventDispatcher(); $dispatcher->addListener(‘event_name‘, function (Event $event) {    // ...}); $dispatcher->dispatch(‘event_name‘);

 

11. dependencyinjection

use Symfony\Component\DependencyInjection\ContainerBuilder;use Symfony\Component\DependencyInjection\Reference; $sc = new ContainerBuilder();$sc    ->register(‘foo‘, ‘%foo.class%‘)    ->addArgument(new Reference(‘bar‘));$sc->setParameter(‘foo.class‘, ‘Foo‘); $sc->get(‘foo‘);

 

12. httpkernel

The HTTP kernel component provides the most dynamic part of the HTTP protocol. The following interface is defined and displayed in the form. It is also the core of the symfony2 framework.

interface HttpKernelInterface{    /**     * Handles a Request to convert it to a Response.     *     * @param  Request $request A Request instance     *     * @return Response A Response instance     */    function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true);}

It accepts a request input and returns a response output. As long as you follow this interface rule, you can use all the wonderful content in symfony2.

 

The following uses the symfony2 component to create a simple framework:

$routes = new RouteCollection();$routes->add(‘hello‘, new Route(‘/hello‘, array(‘_controller‘ =>    function (Request $request) {        return new Response(sprintf("Hello %s", $request->get(‘name‘)));    }))); $request = Request::createFromGlobals(); $context = new RequestContext();$context->fromRequest($request); $matcher = new UrlMatcher($routes, $context); $dispatcher = new EventDispatcher();$dispatcher->addSubscriber(new RouterListener($matcher)); $resolver = new ControllerResolver(); $kernel = new HttpKernel($dispatcher, $resolver); $kernel->handle($request)->send();

OK. This is the framework!

If you want to add an HTTP reverse proxy to obtain the benefits of HTTP caching and ESI, do this!

$kernel = new HttpKernel($dispatcher, $resolver);  $kernel = new HttpCache($kernel, new Store(__DIR__.‘/cache‘));

I want to test the function:

$client = new Client($kernel);$crawler = $client->request(‘GET‘, ‘/hello/Fabien‘); $this->assertEquals(‘Fabien‘, $crawler->filter(‘p > span‘)->text());

Want a nice error display page?

$dispatcher->addSubscriber(new ExceptionListener(function (Request $request) {    $msg = ‘Something went wrong! (‘.$request->get(‘exception‘)->getMessage().‘)‘;     return new Response($msg, 500);}));

You can continue to use your imagination...

 

Let's see how powerful the httpkernelinterface is!

 

To sum up, symfony2 seems awesome. Continue to study !!!

 

 

Follow URL: http://fabien.potencier.org/article/49/what-is-symfony2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.