[SF] Symfony 组件 BrowserKit 原理

直接看下面的注释中针对每一个文件的作用说明。

<?php
/**
 * BrowserKit - Make internal requests to your application.
 *
 * If you need to make requests to external sites and applications, consider using Goutte.
 *
 * Request.php   是一个简单包装请求中的各部分信息的容器,以提供存取。
 * Response.php  是一个简单包装 content, status, headers 的对象,仅仅用于返回,return new Response()。
 * Cookie.php    是一个 cookie 信息的容器,操作逻辑和原生cookie函数基本一致,可以理解为只在程序中传递的 cookie,不是在浏览器中真实设置的 cookie。
 * CookieJar.php 是所有不重复未过期 Cookie对象 的容器,内部设置原理是 $this->cookieJar[$cookie->getDomain()][$cookie->getPath()][$cookie->getName()] = $cookie;
 * History.php   是记录每个 Request对象 的容器,以提供存取,内部设置原理是 $this->stack[] = clone $request; $this->position = count($this->stack) - 1;
 * Client.php    一个模拟浏览器的客户端,内部组合应用 Request, Cookie, CookieJar, History 以及 DomCrawler, Process 组件,Process 实际请求脚本,DomCrawler 实际处理 HTML 文档。
 *
 * 以上容器的概念等同于对象,提供OOP的操作。
 *
 * @see https://symfony.com/doc/current/components/browser_kit.html
 * @author <www.farwish.com>
 */

use SymfonyComponentBrowserKitClient as BaseClient;
use SymfonyComponentBrowserKitResponse;

include __DIR__ . '/../../../vendor/autoload.php';

// Creating a Client.
class Client extends BaseClient
{
    protected function doRequest($request)
    {
        return new Response();
    }
}

// Making Requests.
$client = new Client();
$crawler = $client->request('GET', '/');

print_r($crawler);

小结:

个人感觉 BrowserKit 是一个比较鸡肋的组件,主要用在 application 内部请求以及HTML解析,而且它的功能都是来源于其它两个组件 Process 和 DomCrawler。

如果要模拟请求外部站点,可使用 Goutte 组件,它的功能来源于其它两个大组件 Guzzle 和 DomCrawler,所以文档用法并不详细,原理同 BrowserKit 是一层再包装。

Code:https://github.com/farwish/php-lab/blob/master/lab/symfony/BrowserKit/client.php

Link:http://www.cnblogs.com/farwish/p/8418801.html

原文地址:https://www.cnblogs.com/farwish/p/8418801.html