
PsySH (Tinker), MySQL - документація в консолі
12.03.2021 20:57 | Laravel, Інше
Треба розуміти, що 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
повинна показувати source code, але часто ця опція буде недоступною, проте дана команда підходить для того, щоб по-швидкому нагадати собі сигнатуру. Наприклад:
>>> 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
, нам будуть доступні всі команди, так би мовити, батьківського REPL. При виконанні команди 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. Заходимо (скажімо ми в homestead):
$ 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>
На цьому на сьогодні все. Успіхів!