WEB-Программист
Переключить навигацию

Язык

  • Русский
  • Русский
Связаться с нами

Поиск

  • Книги
  • JavaScript
  • HTML и CSS
  • Другие
  • SEO
  • wordpress
  • Дизайн
  • Laravel
  • Phyton
  • React js
  • Android
  • SQL и языки запросов
  • Yii
  • Шрифты
  • Статьи
  • Laravel
  • wordpress
  • Темы Wordpress
  • Интернет магазин
  • JavaScript
  • © 2015-2026 Andrii Beznosko

  • Hosting CityHost

Расширяем классы Laravel методом `orAbort` при помощи трейта

  • Описания
  • Описание/Скачать

Вдохновлённый статьёй Edd Man’s об опциональных управляющих потоках, я создал небольшой пакет Laravel для реализации опциональной остановки приложения.

Он предоставляет трейт Spatie\OrAbort\OrAbort, который может использоваться с любым классом. Всем методам класса добавляется orAbort функциональность. Когда оригинальный метод возвращает false, будет вызвана функция Laravel abort с 404-м кодом ошибки.

Почему вы захотите использовать этот трейт? Обычно вы могли делать нечто такое:

$article = $articleRepository->find($articleId) ?: abort(404)

 

При использовании трейта код выше превратится в более читаемый:

$article = $articleRepository->findOrAbort($articleId);

Вы даже можете добавить дополнительный параметр с возвращаемым кодом:

$article = $articleRepository->findOrAbort($articleId, 500);

 

Если метод find нашего репозитория возвратит false, Laravel остановит приложение с кодом 500.

Трейт orAbort использует магический метод __call. Не применяйте его в классах, которые уже используют этот метод.

Найти пакет можно на GitHub.

Комментарии
Всего комментариев: 0
Оставить комментарий Отменить ответ

Ваш email не будет опубликован.

Жанр: Главная » Статьи » Laravel » Расширяем классы Laravel методом `orAbort` при помощи трейта
Статус: Для продвинутых программистов
Ссылка на оригинал статьи (Если указана или эта статья не авторская) Скачать
На сайт предоставил Сен 18, 2015 13:13 Andriy

Статьи опубликованные на сайте WEB-Программист указаны со ссылками на источник. Администрация сайта не несет ответственность за их использование Вами

Laravel
Previous Next

Смотри также:

Изменяем стандартную страницу ошибки в Laravel 5.1

Всем нам знакома страница Whoops, looks like something went wrong. Мы можем легко модифицировать её под нужды нашего клиентского шаблона. Для этого достаточно изменить файл app/Exceptions/Handler.php, переопределив в классе Handler методconvertExceptionToResponse: <?php namespace App\Exceptions; use Exception; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;...

Способы организации пространств имён классов в Laravel

В коде: <?php namespace App; class SendReceipt {}   Структура папок: src Receipt ReceiptRepository SendReceipt SendReceiptHandler User UserRepository CreateUser CreateUserHandler   Преимущества: Проще не иметь дело с подпространствами имён. В очень маленьких приложениях это может быть нормально. Если у вас...

Уроки по Laravel 5

Доброго времени суток, сегодня ми поговорим о таком замечательном фреймворке как laravel 5. Ниже приведен курс уроков от loftblog В нем расскажут про создания гостевой книги Урок 1 Гостевая книга на Laravel 5.1 - #1 Начало https://www.youtube.com/watch?v=yA_28ab3Q8I Урок 2 Гостевая...

Создание пакетов для Laravel

Prosper Otemuyiwa недавно написал статью о том, как создавать пакеты для Laravel 5 в своём блоге. Хотя его способ абсолютно правильный и может вам подходить, я предпочитаю немного иной способ создания пакетов. Сначала я создаю новый репозиторий на GitHub. В...

Структура приложения и пространств имён при DDD в Laravel

Я обычно разделяю большие приложения на 4-5 пространств имён, которые привязаны к глобальному app пространству имён. Например, я хочу создать приложение ToDo List, так что базовое пространство имён будет ToDo. Затем у меня есть 3 пространства имён внутри этого: App...

Связаться с нами

- Премиум темы и плагины WP Star бесплатно -

We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Cookie settingsACCEPT
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT