向鲍里斯问好:PHP的更好REPL

As web developers, we know the importance of the JavaScript console provided by the browser in testing out code snippets. We don’t need to write an entire HTML page and JavaScript code just to verify the functioning or logic of a small routine we wrote. Instead, we simply run the expressions in the console and immediately see the results.

作为Web开发人员,我们知道浏览器提供JavaScript控制台在测试代码段中的重要性。 我们不需要编写整个HTML页面和JavaScript代码就可以验证我们编写的小例程的功能或逻辑。 相反,我们只需在控制台中运行表达式并立即查看结果。

Similarly, a REPL (Read-Eval-Print Loop) is the console of a programming language in which we can write code line-by-line and see what it does. PHP has a REPL; if you haven’t used it yet, run php –a in a terminal. This will take you to the interactive PHP prompt at which you can enter your code.

同样,REPL(读取评估打印循环)是一种编程语言的控制台,在该控制台中,我们可以逐行编写代码并查看其功能。 PHP具有REPL; 如果尚未使用过,请在终端中运行php –a 。 这将带您到交互式PHP提示符,您可以在其中输入代码。

$ php -a
Interactive shell

php > echo "Hello REPL";
Hello REPL

All programming language REPLs work essentially the same way. There is an infinite loop which essentially processes three tasks: a read task that reads in an expression entered at the prompt, an eval function that parses and executes the expression, and an print function to display the results of the action.

所有编程语言REPL的工作方式基本上相同。 有一个无限循环,该循环本质上处理三个任务:一个读取任务,用于读取在提示符下输入的表达式;一个eval函数,用于解析和执行该表达式;以及一个print函数,用于显示操作结果。

PHP’s REPL is very good in what it does, although it does have some limitations. For example, it doesn’t handle errors very well; the REPL exits back to console whenever a fatal occurs. Another drawback of PHP’s default REPL compared to other languages’ is that it doesn’t output the result of an expression to the console; we have to explicitly tell it to echo or print the result. Most other REPLs always output the result of an expression to the console.

PHP的REPL的功能非常出色,尽管它确实有一些局限性。 例如,它不能很好地处理错误。 每当发生致命事故时,REPL都会返回控制台。 与其他语言相比,PHP的默认REPL的另一个缺点是它不会将表达式的结果输出到控制台。 我们必须明确地告诉它回显或打印结果。 大多数其他REPL始终将表达式的结果输出到控制台。

And so, Boris tries to solve these problems and other concerns as well. Boris is a tiny PHP REPL library written in PHP by Chris Corbyn. It handles fatal errors more efficiently in that it won’t exit the console when an error occurs. Instead, it reports the error details and stack trace in the console. Boris also outputs the results of evaluating an expression.

因此, 鲍里斯(Boris)试图解决这些问题和其他问题。 Boris是Chris Corbyn用PHP编写的微型PHP REPL库。 它可以更有效地处理致命错误,因为发生错误时它不会退出控制台。 而是在控制台中报告错误详细信息和堆栈跟踪。 鲍里斯(Boris)还输出评估表达式的结果。

安装 (Installation)

Boris is hosted on GitHub, so it’s easy to install using Git. Note that Boris requires the PCNTL extension, so if it’s not already available on your machine then you can follow these steps to get it installed. Then, clone Boris to your machine.

Boris托管在GitHub上,因此可以使用Git轻松安装。 请注意,鲍里斯(Boris)需要PCNTL扩展名,因此,如果您的计算机上尚未提供该扩展名,则可以按照以下步骤进行安装。 然后,将Boris克隆到您的计算机上。

$ git clone git://github.com/d11wtq/boris.git

This will clone the entire Boris library into a new directory boris in your current location, which contains an executable PHP script to load and run Boris. (Boris can be installed using Composer as well, which I’ll show you later.)

这会将整个Boris库克隆到当前位置的新目录boris中,该目录包含一个用于加载和运行Boris的可执行PHP脚本。 (也可以使用Composer来安装Boris,稍后将向您展示。)

To start using Boris, step inside the directory and run the script.

要开始使用Boris,请进入目录并运行脚本。

$ cd boris
$ ./bin/boris

This will take you to the Boris prompt. Just as with the default PHP prompt, we can enter the code here and run. Let’s try some simple expressions.

这将带您到Boris提示符。 就像默认PHP提示符一样,我们可以在此处输入代码并运行。 让我们尝试一些简单的表达式。

[1] boris> $timezone = new DateTimeZone("America/New_York");
→ object(DateTimeZone)#5 (0) {
}

[2] boris> $date =  new DateTime("now", $timezone);
→ object(DateTime)#6 (3) {
  ["date"]=>
  string(19) "2013-03-29 23:56:25"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(16) "America/New_York"
}

The result of an expression is always returned back to the console which helps us to inspect values/objects as soon as they are created.

表达式的结果总是返回到控制台,这有助于我们在值/对象创建后立即对其进行检查。

For easier access, you can add the path to the Boris script in your .bashrc (or similar) and reloading your shell environment. Then you’ll be able to run boris from anywhere in your terminal and be taken to the Boris prompt.

为了更轻松地访问,您可以在.bashrc (或类似文件)中将Boris脚本的路径添加到并重新加载Shell环境。 然后,您将可以在终端的任何位置运行boris ,并转到Boris提示符下。

export PATH="path/to/boris/bin:$PATH"

定制鲍里斯 (Customizing Boris)

An important feature of Boris is the ability to customize its features. If you look at the content of the ./bin/boris file, you’ll find it’s just a PHP file that initializes a Boris instance. We can change the default prompt by passing it in the constructor.

Boris的一个重要功能是可以自定义其功能。 如果查看./bin/boris文件的内容,您会发现它只是一个初始化Boris实例PHP文件。 我们可以通过在构造函数中传递默认提示来更改它。

$boris = new BorisBoris('app $ ');
$boris->start();

But customization is not just limited to the prompt. We can also define some default variables to be available inside the REPL, with something like this:

但是自定义不仅限于提示。 我们还可以定义一些默认变量以在REPL中使用,如下所示:

$boris->setLocal("myVar", "Value");

We can then refer to the value with $myVar, which would help us avoid defining various variables every time we use Boris.

然后,我们可以使用$myVar来引用该值,这将有助于避免每次使用Boris时定义各种变量。

By default, Boris shows results using var_dump(), but we can use our own inspectors to customize the REPL’s output. If you prefer some other format, create a class that implements the Inspector interface, which has a method called inspect().

默认情况下,鲍里斯var_dump() Boris var_dump()使用var_dump()显示结果,但是我们可以使用自己的检查器来自定义REPL的输出。 如果您喜欢其他格式,请创建一个实现Inspector接口的类,该类具有一个名为inspect()的方法。

class MyInspector implements Inspector {
    public function inspect($variable) {
        ob_start();
        print_r($variable);
        return trim(ob_get_clean());
    }
}

$boris->setInspector(new MyInspector());

您的应用程序中的REPL (A REPL in your Application)

Boris can easily be embedded into your standalone PHP application or library as well. As an example, let’s create a command-line web service client using Boris and Guzzle. Guzzle is a powerful library for creating Web service clients and provides a simple interface for making API requests programmatically.

Boris可以轻松地嵌入到独立PHP应用程序或库中。 作为示例,让我们使用Boris和Guzzle创建一个命令行Web服务客户端。 Guzzle是用于创建Web服务客户端的功能强大的库,并提供了用于以编程方式发出API请求的简单界面。

First, create a composer.json file to set up the required libraries.

首先,创建一个composer.json文件来设置所需的库。

{
    "require": {
        "d11wtq/boris": "dev-master",
        "guzzle/guzzle": "~3.1"
    }
}

Then install these dependencies using Composer. This will download Boris, Guzzle, and their dependencies to a vendor folder in the current directory.

然后使用Composer安装这些依赖项。 这会将Boris,Guzzle及其依赖项下载到当前目录中的vendor文件夹中。

$ composer.phar install

Next, create an executable script (I’ve named it wsclient) that will launch our application.

接下来,创建一个可执行脚本(我将其命名为wsclient ),它将启动我们的应用程序。

#!/usr/bin/env php
<?php
// composer autoloader
require "vendor/autoload.php";
use GuzzleHttpClient;

// Initialize Boris with our own prompt.
$boris = new BorisBoris("wsclient > ");

// Guzzle client with our API base URL
$client = new Client("http://myapplication/api");

// We don't want to create the Client object every time.
$boris->setLocal("client", $client);

// Default inspectors are bit noisy. Let's override that.
$boris->setInspector(new GuzzleInspector());

// Start the REPL
$boris->start();

We’ve included the autoloader provided by Composer which makes things easier. Then we’ve initialized Boris and created a Guzzle client explicitly for our web service so that we don’t need to do this over and over again. The client object is made available inside the REPL by setting it as a local variable with setLocal(). We aren’t interested in inspecting the variables and objects here, so we’ve overridden the default inspector with GuzzleInspctor. You can create one that will help you to debug responses from server, but the one I’ve created for the example looks like this:

我们包含了Composer提供的自动加载器,这使事情变得更加容易。 然后,我们初始化了Boris并为我们的Web服务显式创建了一个Guzzle客户端,这样我们就不必一遍又一遍地执行此操作。 通过使用setLocal()将其设置为局部变量,可以在REPL内部使用该客户端对象。 我们对检查变量和对象不感兴趣,因此我们已使用GuzzleInspctor覆盖了默认检查GuzzleInspctor 。 您可以创建一个可以帮助您调试来自服务器的响应的工具,但是我为该示例创建的工具看起来像这样:

<?php
class GuzzleInspector implements BorisInspector
{
    public function inspect($var) {
        ob_start();
        echo (bool) $var;
        return trim(ob_get_clean());
    }
}

Make the script executable, and then start the REPL and try some things out.

使脚本可执行,然后启动REPL并尝试一些操作。

$ chmod +x wsclient
$ ./wsclient

[1] wsclient > $request = $client->get("/user")->setAuth("user", "pass");
 → true
[2] wsclient > $response = $request->send();
 → true
[3] wsclient > echo $response->getBody();
//{"login":"user","id":123000,"avatar_url":"...

结论 (Conclusion)

I don’t need to explain the real power of a REPL if you’ve ever used Python, Ruby, Scala, OCaml, or any other language that offers one. A REPL is a great tool when first learning a language, and also when testing and debugging various code snippets.

如果您曾经使用过Python,Ruby,Scala,OCaml或其他任何提供该语言的语言,则无需解释REPL的真正功能。 当初学语言时,以及在测试和调试各种代码段时,REPL是一个很好的工具。

Like many other mainstream languages, PHP has a REPL, but it has some drawbacks, especially in error handling. Boris is a tiny library, which tries to fill in its gap. More interestingly, you can easily create a CLI for your applications using Boris.

像许多其他主流语言一样,PHP具有REPL,但它也有一些缺点,尤其是在错误处理方面。 鲍里斯(Boris)是一个很小的图书馆,试图填补空白。 更有趣的是,您可以使用Boris轻松为您的应用程序创建CLI。

Although Boris is really cool and pretty useful at times, it does have some limitations of it’s own, too. Boris depends on the forking capability of the operating system, so it can’t be used in Windows. Also, as of now it’s not a bulletproof application. There are some issues that need to be fixed, and some more features like auto-completion of function names and class methods would be handy.

尽管鲍里斯(Boris)确实很酷并且有时很有用,但它也有其自身的局限性。 鲍里斯(Boris)取决于操作系统的分叉功能,因此不能在Windows中使用。 另外,到目前为止,它还不是防弹应用程序。 有一些问题需要解决,一些其他功能(如自动完成功能名称和类方法)将很方便。

I hope you will find many other use cases of this library; feel free to share them in the comment section below.

我希望您会发现该库的许多其他用例; 请随时在下面的评论部分中分享它们。

Image via Fotolia

图片来自Fotolia

翻译自: https://www.sitepoint.com/say-hello-to-boris-a-better-repl-for-php/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值