PsySH (Tinker), MySQL - документация в консоли

PsySH (Tinker), MySQL - документация в консоли

Надо понимать, что laravel/tinker является надстройкой PsySH - консоли разработчика, интерактивного дебаггера и REPL для PHP.  Как добавить документацию, Вы можете найти здесь, но тем не менее рассмотрим процесс пошагово. 

Сразу уточню: предполагается, что работаем под Ubuntu. Будем отталкиваться от того, что помимо tinker, мы хотим и напрямиую использовать PsySH, поэтому установим пакет глобально:

composer global require psy/psysh:@stable

 

Поскольку мы хотим запускать psysh из любой локации, убедимся, что composer добавлен в переменную PATH:

export PATH="~/.composer/vendor/bin:$PATH"

 

Последний шаг - загрузить документацию php. Выполняем:

mkdir -p ~/.local/share/psysh/

 

И затем:

wget -O ~/.local/share/psysh/php_manual.sqlite http://psysh.org/manual/en/php_manual.sqlite

 

Собственно, всё. Запускаем консоль командой psysh, в результате чего должны увидеть следующее:

$ psysh
Psy Shell v0.10.6 (PHP 8.0.3 — cli) by Justin Hileman
>>>

 

Фактически нас интересуют команды show и doc, для того же, чтобы увидеть все команды, введём help:

$ psysh
Psy Shell v0.10.6 (PHP 8.0.3 — cli) by Justin Hileman
>>> help
  help       Show a list of commands. Type `help [foo]` for information about [foo].      Aliases: ?                     
  ls         List local, instance or class variables, methods and constants.              Aliases: dir                   
  dump       Dump an object or primitive.                                                                                
  doc        Read the documentation for an object, class, constant, method or property.   Aliases: rtfm, man             
  show       Show the code for an object, class, constant, method or property.                                           
  wtf        Show the backtrace of the most recent exception.                             Aliases: last-exception, wtf?  
  whereami   Show where you are in the code.                                                                             
  throw-up   Throw an exception or error out of the Psy Shell.                                                           
  timeit     Profiles with a timer.                                                                                      
  trace      Show the current call stack.                                                                                
  buffer     Show (or clear) the contents of the code input buffer.                       Aliases: buf                   
  clear      Clear the Psy Shell screen.                                                                                 
  edit       Open an external editor. Afterwards, get produced code in input buffer.                                     
  sudo       Evaluate PHP code, bypassing visibility restrictions.                                                       
  history    Show the Psy Shell history.                                                  Aliases: hist                  
  exit       End the current session and return to caller.                                Aliases: quit, q               
>>>

 

На досуге рекомендую ознакомиться/поэкспериментировать со всеми командами. А теперь, собственно, то, ради чего всё затевалось. Как видите выше, команда show должна показывать исходники, но зачастую исходники будут недоступны, тем не менее данная команда подходит для того, чтобы по-быстрому напомнить себе сигнатуру. Например:

>>> show number_format
function number_format(float $num, int $decimals = 0, string $decimal_separator = '.', string $thousands_separator = ','): string
Source code unavailable
>>>

 

Используем команду doc:

>>> doc number_format
function number_format(float $num, int $decimals = 0, string $decimal_separator = '.', string $thousands_separator = ','): string

Description:
  Format a number with grouped thousands
  
  This function accepts either one, two, or four parameters (not three):
  
  If only one parameter is given, $number will be formatted without decimals, but with a comma (",")
  between every group of thousands.
  
  If two parameters are given, $number will be formatted with $decimals decimals with a dot (".") in
  front, and a comma (",") between every group of thousands.
  
  If all four parameters are given, $number will be formatted with $decimals decimals, $dec_point
  instead of a dot (".") before the decimals and $thousands_sep instead of a comma (",") between
  every group of thousands.

Param:
  float   $number         The number being formatted.
  int     $decimals       Sets the number of decimal points.
  string  $dec_point      Sets the separator for the decimal point.
  string  $thousands_sep  Sets the thousands separator.

Return:
  string  A formatted version of $number.

See Also:
   * money_format()
   * sprintf()
   * printf()
   * sscanf()

>>>

 

Разумеется, документацию Laravel мы не сможем посмотреть в psysh. Для этого нужно запустить php artisan tinker из корня какого-либо laravel проекта. Повторюсь: посколько tinker является надстройкой над psysh, нам будут доступны все команды, так сказать, родителя. При выполнении команды show для laravel классов, объектов, свойств и методов, нам будет доступен исходный код. Например: 

>>> show throw_unless
295:     /**
296:      * Throw the given exception unless the given condition is true.
297:      *
298:      * @param  mixed  $condition
299:      * @param  \Throwable|string  $exception
300:      * @param  array  ...$parameters
301:      * @return mixed
302:      *
303:      * @throws \Throwable
304:      */
305:     function throw_unless($condition, $exception = 'RuntimeException', ...$parameters)
306:     {
307:         if (! $condition) {
308:             if (is_string($exception) && class_exists($exception)) {
309:                 $exception = new $exception(...$parameters);
310:             }
311: 
312:             throw is_string($exception) ? new RuntimeException($exception) : $exception;
313:         }
314: 
315:         return $condition;
316:     }

>>> 

 

...и команда doc:

>>> doc throw_unless
function throw_unless($condition, $exception = 'RuntimeException', $parameters = unknown)

Description:
  Throw the given exception unless the given condition is true.

Throws:
  \Throwable 

Param:
  mixed              $condition     
  \Throwable|string  $exception     
  array              ...$parameters 

Return:
  mixed 
>>>

 

Внимание: как Вы догадываетесь, документацию laravel можно смотреть и без установки psysh и загрузки php-доков.

И небольшой бонус - как вывести документацию в консоли MySQL. Заходим в консоль:

$ mysql -u homestead -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
...
mysql>

 

Всё, что нужно - использовать команду help + название функции, типа данных и т.д. Например:

mysql> help concat_ws;
Name: 'CONCAT_WS'
Description:
Syntax:
CONCAT_WS(separator,str1,str2,...)

CONCAT_WS() stands for Concatenate With Separator and is a special form
of CONCAT(). The first argument is the separator for the rest of the
arguments. The separator is added between the strings to be
concatenated. The separator can be a string, as can the rest of the
arguments. If the separator is NULL, the result is NULL.

URL: https://dev.mysql.com/doc/refman/5.7/en/string-functions.html

Examples:
mysql> SELECT CONCAT_WS(',','First name','Second name','Last Name');
        -> 'First name,Second name,Last Name'
mysql> SELECT CONCAT_WS(',','First name',NULL,'Last Name');
        -> 'First name,Last Name'

mysql>

 

или:

mysql> help mediumint;
Name: 'MEDIUMINT'
Description:
MEDIUMINT[(M)] [UNSIGNED] [ZEROFILL]

A medium-sized integer. The signed range is -8388608 to 8388607. The
unsigned range is 0 to 16777215.

URL: https://dev.mysql.com/doc/refman/5.7/en/numeric-type-syntax.html


mysql>

 

Что важно, можно вывести список всего контента, по которому можно посмотреть справочную информацию (там много чего помимо типов данных и функций): 

mysql> help contents;
You asked for help about help category: "Contents"
For more information, type 'help <item>', where <item> is one of the following
categories:
   Account Management
   Administration
   Compound Statements
   Contents
   Data Definition
   Data Manipulation
   Data Types
   Functions
   Geographic Features
   Help Metadata
   Language Structure
   Plugins
   Procedures
   Storage Engines
   Table Maintenance
   Transactions
   User-Defined Functions
   Utility

mysql>

 

На этом на сегодня всё. Успехов!