Laravel php artisan tinker

Полное руководство по Tinker

tinker

Недооцененный встроенный Laravel-компонент — команда php artisan tinker , которую используют для запуска кода в контексте приложения. Давайте разберемся, на что она способна.

Tinker — это REPL ( read-eval-print loop — цикл «чтение-вычисление-вывод») поверх PsySH. Он принимает данные из командной строки, обсчитывает их и выводит в консоль. Поэтому вместо того, чтобы использовать инструменты управления базой данных и писать SQL-запросы для получения количества пользователей, вы можете просто запустить App\User::count() и получить результат => 10 .

Как он работает?

Команда php artisan tinker загружает ваше приложение и ожидает ввода команд. Она хранит состояние приложения, пока вы не набрали exit , Ctrl+C или просто не закрыли терминал. Это означает, что вам нужно инициализировать новую tinker-сессию каждый раз, как вы изменяете свой код, но это также позволяет вам задавать новые переменные, которые доступны до тех пор, пока вы не завершите сессию.

Читайте также:  Команда pop в питоне

Когда это может понадобиться?

Всегда! Мы используем Tinker во множестве случаев и в цикле разработке и на продакшене. Наиболее распространенный вариант использования — доступ к базе данных через Laravel Eloquent Модели.

Использование Eloquent Моделей в Tinker

Tinker очень удобен для создания тестовых данных в процессе разработки. Например, быстро создадим двух новых тестовых пользователей с фабрикой.

Эта команда использует фабрику моделей для пользователей и создает двух новых. Вывод этой команды должен выглядеть примерно так — с рандомными именами и адресами.

=> Illuminate\Database\Eloquent\Collection , App\Models\User , ], >

Давайте изменим фамилию второго пользователя через php artisan tinker (введите и подтвердите каждую строку отдельно)

$user = User::where('email', 'trycia.koelpin@example.org')->first(); $user->lastname = 'Smith'; $user->save();

Если это сработает, то Tinker вернет => true .

Если нет желания запускать по одной команде, а модель поддерживает массовые назначения, то вы можете запустить это одной строкой.

User::where('email', 'trycia.koelpin@example.org')->first()->update(['lastname' => 'Carlson']);

Нет никаких ограничений на работу с Tinker, пока вы можете втиснуть свой код в одну строку или выполнять его построчно. С ним у вас есть доступ ко всем PHP-функциям и Laravel-хелперам.

Генерация UUID

Вместо того, чтобы гуглить интернет-сервис, который сгенерирует вам UUID, вы можете использовать Tinker и получить его с помощью хелпера Str.

=> Ramsey\Uuid\Lazy\LazyUuidFromString

Создание слага из заголовка

Str::slug('The ultimate guide to php artisan tinker')
=> "the-ultimate-guide-to-php-artisan-tinker"

Получение даты первого дня недели через 3 месяца

=> Illuminate\Support\Carbon @1627862400

Кодирование и декодирование Base64

base64_encode('The ultimate guide to php artisan tinker') base64_decode('VGhlIHVsdGltYXRlIGd1aWRlIHRvIHBocCBhcnRpc2FuIHRpbmtlcg==')
=> "VGhlIHVsdGltYXRlIGd1aWRlIHRvIHBocCBhcnRpc2FuIHRpbmtlcg==" => "The ultimate guide to php artisan tinker"

Отправка задач

С помощью Tinker вы можете отправлять задачи и добавлять в них данные. Это реальная экономия времени, когда вы разрабатываете новую задачу, и для ее запуска требуется несколько шагов. Представьте, что у вас есть задача, которая осуществляет заказ в системе электронной торговли. При тестировании задачи вы можете создать много заказов или просто отправить ее через Tinker. Не забудьте перезапустить сессию, если меняете код задачи.

$order = new Order(['invoice_id' => 12345, 'item' => 'Tinker Fangirl Mug']); dispatch(new OrderPlacedJob($order));

Отправка уведомлений

Как и в случае с задачами, вы также можете отправлять через Tinker уведомления и рассылки. В контексте своего приложения это делается простым вызовом.

(new User)->notify(new InvoicePaid($invoice);

Проверка текущей версии Laravel

Файл composer.json содержит версию Laravel-приложения Laravel. Вы можете легко узнать её вызвав:

Tinkerwell — Tinker на стероидах

Вы можете вывести Tinker на ещё более мощный уровень. Представляем вам Tinkerwell — редактор кода для macOS, Windows и Linux, который полностью посвящен Tinker. Он поддерживает многострочность, SSH-соединения и позволяет работать с несколькими приложениями одновременно.

С Tinkerwell нет необходимости перезагружать tinker-сессию, поскольку он самостоятельно оценивает текущее состояние вашего кода и не сохраняет состояние приложения.

Использование коллекций

Многострочная поддержка упрощает использование Laravel-коллекций и foreach-циклов. Например, с помощью коллекций, вы можете обновить несколько пользователей одновременно:

App\User::whereNull('confirmed_at') ->get() ->each(function ($user) < $user->update([ 'confirmed_at' => $user->created_at->addDay(), ]); >);

Тестирование API

При работе с API, Http -фасад в Laravel предоставляет интерфейс для отправки GET и POST запросов. С помощью него вы можете получить доступ к API, посмотреть, как выглядят у него данные, или отправить свои данные до того, как реализовывать его непосредственно в своем приложении.

$apiKey = 'Your-Forge-API-Key'; $response = Http::withHeaders([ 'accept' => 'application/json' ]) ->withToken($apiKey) ->get('https://forge.laravel.com/api/v1/servers') ->json(); collect($response['servers'])->pluck('name');

=> Illuminate\Support\Collection

Наш Телеграм-канал — следите за новостями о Laravel.

Задать вопросы по урокам можно на нашем форуме.

Источник

The ultimate guide to php artisan tinker

Tinkerwell background image Tinkerwell background image

This post is dedicated to an underappreciated component of Laravel – the tinker command that you can run with php artisan tinker . The command is built into every Laravel application and you can use it to run code within the context of your application. Let’s explore what this means.

Tinker is a REPL (read-eval-print loop) on top of PsySH. It takes your command line input, evaluates it and prints the output to the console. So instead of using your database management tool and writing an SQL query to get the amount of users in your database, you can simply run App\User::count() and get => 10 as the result.

Tinkerwell –
php artisan tinker on steroids

Tinker with autocompletion, a multi-line code editor, code snippets and magic comments.

How does it work?

The php artisan tinker command bootstraps your application and waits for new commands when this finishes. It keeps the application state until you close leave the tinker command with exit , Ctrl+C or close the terminal. This means that you have to initialize a new tinker session every time you change your code to get the latest version – but it allows you to define new variables that are accessible until you end the tinker session.

When do you need it?

All the time! We use tinker in development and on production for many scenarios. The most common use case is accessing the database via Laravel Eloquent Models.

Use Eloquent Models with tinker

Tinker is very convenient if you want to create test data in development – simply create two new test users with their factory.

This command uses the model factory for users and creates two new users. Your output of this command should look similar to this – with different usernames and emails.

=> Illuminate\Database\Eloquent\Collection [email protected]", >, App\Models\User [email protected]", >, ], > 

Let’s change the last name of the second user with php artisan tinker (type and confirm every line separately)

$user = User::where('email', '[email protected]')->first(); $user->lastname = 'Smith'; $user->save(); 

If this works, tinker returns => true

If you don’t want to run multiple commands and the model supports mass assignments, you can run this in a single line.

User::where('email', '[email protected]')->first()->update(['lastname' => 'Carlson']); 

There are no limits what you can do with tinker as long as you are able to squeeze your code into one line or can execute the code line by line. If you want to push this to the next level, you can use Tinkerwell to write multiple lines of code and run them at once. This is very handy if you work with Laravel Collections or use loops – or simply like well-formatted code.

With tinker, you have access to all PHP functions and helpers that Laravel provides.

Generate UUIDs

Instead of googling for an internet service that lets your generate UUIDs, you can use tinker and generate one with the Laravel Str helper.

This instantly generates an UUID for you.

=> Ramsey\Uuid\Lazy\LazyUuidFromString

Create a slug from a headline

Str::slug('The ultimate guide to php artisan tinker') 
=> "the-ultimate-guide-to-php-artisan-tinker" 

Get the date of the first day of the week in 3 months

=> Illuminate\Support\Carbon @1627862400

Base64 encode and decode

base64_encode('The ultimate guide to php artisan tinker') base64_decode('VGhlIHVsdGltYXRlIGd1aWRlIHRvIHBocCBhcnRpc2FuIHRpbmtlcg==') 
=> "VGhlIHVsdGltYXRlIGd1aWRlIHRvIHBocCBhcnRpc2FuIHRpbmtlcg==" => "The ultimate guide to php artisan tinker" 

Dispatch jobs

You can dispatch jobs with tinker and add data to this job too. This is a real time-saver when you develop a new job and there are multiple steps involved to trigger the job. Imagine that you have a job that fulfills an order in an ecommerce system. You can either place many orders to test the job or simply dispatch it via tinker. Remember to restart your tinker session if you change the code of the job – or dispatch the job with Tinkerwell where every command runs on the latest code base.

$order = new Order(['invoice_id' => 12345, 'item' => 'Tinker Fangirl Mug']); dispatch(new OrderPlacedJob($order)); 

Send Notifications

Similar to Jobs, you can also send Laravel Notifications & Mailables via tinker. You are in the context of your application and can send them with a simple call.

(new User)->notify(new InvoicePaid($invoice); 

Check your current Laravel version

The composer.json file of your application contains the major and minor version of your Laravel application. If you want to know which Laravel version you use exactly, you can get this via app()->version() .

Tinkerwell – php artisan tinker on steroids

Tinker is a powerful tool for all Laravel developers but you can push this to a next level. Tinkerwell is a code editor for macOS, Windows and Linux that is entirely dedicated to tinker. It comes with multiline support, SSH connections and allows you to tinker with multiple applications at the same time.

With Tinkerwell, there is no need to reload a tinker session, as Tinkerwell evaluates the current state of your code and does not keep the application state.

Using Collections

The multiline support makes it easy to use Laravel Collections or foreach loops in tinker. To continue with an example, you can update multiple users at the same time by using collections on the Eloquent result.

App\User::whereNull('confirmed_at') ->get() ->each(function ($user) < $user->update([ 'confirmed_at' => $user->created_at->addDay(), ]); >); 

Testing APIs

When working with APIs, the Http facade of Laravel provides a fluent interface to send GET and POST requests to an API. You can use this to access the API and see how the data of this API looks or send data to the API before you implement the API directly in your application.

$apiKey = 'Your-Forge-API-Key'; $response = Http::withHeaders([ 'accept' => 'application/json' ]) ->withToken($apiKey) ->get('https://forge.laravel.com/api/v1/servers') ->json(); collect($response['servers'])->pluck('name'); 
=> Illuminate\Support\Collection

Tinkerwell is a mighty desktop application for every Laravel developer and more than 10,000 developers are already using Tinkerwell, including the Laravel team itself.

Tinkerwell: The code runner for PHP

The must-have companion to your favorite IDE. Quickly iterate on PHP code within the context of your web application.

Tinkerwell

The code runner for PHP.
Loved by developers like you.

Источник

Оцените статью