Блог Серії
Кар'єра
Вакансії Компанії
Навчання
Співбесіди Тестування Відео
Екосистема
Пакети Ресурси Проєкти
Інше
Події Про нас
Патерн Decorator
Посібники 26 червня 2026
2

Decorator - middleware як обгортка

Decorator додає об'єкту нову поведінку, обгортаючи його в інший об'єкт із тим самим інтерфейсом, без змін у базовому компоненті.

Яку проблему вирішує

Коли потрібно нарощувати функціональність (логування, кешування, авторизація), спадкування дає вибух підкласів на кожну комбінацію можливостей. До того ж поведінку часто хочеться вмикати динамічно й комбінувати у довільному порядку.

Як вирішує

Декоратор реалізує той самий інтерфейс, що й обгорнутий об'єкт, виконує свою частину роботи й делегує решту далі. Шари накладаються один на одного, тож поведінка комбінується композицією, а не спадкуванням.

У Laravel ця ідея природно виглядає як Middleware: кожен middleware обгортає наступний і додає поведінку. Формально middleware - це framework-реалізація ідей Decorator та Chain of Responsibility.

use Closure;
use Illuminate\Http\Request;

class LogTime
{
  public function handle(Request $request, Closure $next)
  {
    $start = microtime(true);
    $response = $next($request);
    $ms = (microtime(true) - $start) * 1000;
    logger()->info('req ms', ['ms' => $ms]);

    return $response;
  }
}

// Застосувати middleware напряму за класом:
Route::middleware(LogTime::class)
  ->get('/orders', [OrderController::class, 'index']);

// Або зареєструвати аліас у bootstrap/app.php (Laravel 11+):
->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'log.time' => LogTime::class,
    ]);
})

Route::middleware('log.time')->get('/', HomeController::class);

Де застосовувати

  • Кросфункціональні задачі: логування, кешування, авторизація, rate-limit.
  • Коли поведінку треба вмикати опціонально й комбінувати у різному порядку.

Плюси та мінуси

  • + Логіка додається шарами і легко комбінується без вибуху підкласів.
  • + Композиція гнучкіша за спадкування - шари вмикаються динамічно.
  • Порядок шарів важливий і його треба контролювати.
  • Багато дрібних обгорток ускладнюють відлагодження стека викликів; тримайте кожен декоратор маленьким і відповідальним за одну річ.

Ця стаття - частина серії

Патерни проєктування

9 / 9

Коментарі

Увійдіть, щоб залишити коментар

Будьте першим, хто залишить коментар!

Читайте також

Патерн Composite
Посібники 23 червня 2026
Патерни проєктування

Composite - дерево об'єктів

Патерн Composite дозволяє працювати з деревом об'єктів так само, як з одним об'єктом. І окремий «лист», і «гілка» (група) реалізують той самий інтерфейс, тож клієнт викликає в них однакові методи.

Патерн Bridge
Посібники 20 червня 2026
Патерни проєктування

Bridge - відокремлення абстракції

Патерн Bridge розділяє абстракцію та її реалізацію на дві окремі ієрархії, щоб змінювати їх незалежно. Це рятує, коли є кілька незалежних вимірів варіативності і за наївного підходу класи множаться комбінаторно.

Вакансії за темою

Full-time Вчора

Middle PHP Developer

ConveyThis Віддалено За результатами співбесіди

Technologies: PHP, Laravel, JavaScript, SQL/NoSQL, GIT, and Bootstrap Minimum Requirements & Job Information: Experience: 3+ years Work Mode: 100% Remote (Work from anywhere) Location: Open to candidates worldwide Countries Considered: No restrictions on location Industry: SaaS (Software as a Service) Startup Environment: Fast-paced, innovative, and collaborative Middle PHP Developer (Remote, SaaS Startup) ConveyThis is seeking a skilled and motivated Middle PHP Developer to join our growing team. This is a fully remote position, but candidates must be available to work New York time (10:00 AM - 7:00 PM EST). If you’re passionate about building scalable web applications and enjoy working in a fast-moving startup environment, we’d love to hear from you! What You’ll Do: Develop, maintain, and optimize high-performance web applications using PHP (Laravel), SQL/NoSQL, JavaScript, and Bootstrap. Ensure code quality, security, and scalability across all projects. Collaborate with designers, product managers, and other developers to design and implement new features. Identify and resolve performance bottlenecks and technical issues. Write well-structured, maintainable, and efficient code. Use GIT for version control and ensure smooth deployment workflows. What We’re Looking For: 3+ years of professional experience in PHP development, Laravel. Strong understanding of SQL/NoSQL databases and data architecture. Proficiency in JavaScript and front-end frameworks, with experience using Bootstrap. Experience working with GIT in a collaborative development environment. Strong grasp of object-oriented programming and clean coding principles. Excellent problem-solving skills and attention to detail. Intermediate or higher English proficiency (ability to communicate clearly in a remote setting). Who You Are: You’re a self-driven developer who thrives in a remote-first startup environment. You’re eager to learn and adapt to new technologies and best practices. You enjoy working collaboratively and value open communication. You take ownership of your work and are committed to delivering high-quality code. Why Join ConveyThis? ConveyThis is a leading AI-powered translation and localization platform, making website translation seamless and efficient. Our cutting-edge technology ensures high-quality, automated translations, while allowing for customization and human refinement. As a company at the forefront of AI-driven website localization, we continuously innovate to provide businesses with the best multilingual solutions for global reach. We foster a culture of creativity, collaboration, and continuous growth. As a fully remote company, we offer flexibility while maintaining a strong team-oriented environment. Our solutions empower businesses to expand internationally by offering SEO-optimized multilingual content, improving global user experience, and driving higher search rankings across multiple markets. If you’re looking to make an impact in a dynamic startup environment, this is the place for you. Interview Process: Introductory call with our recruiter. Technical test assignment to assess your coding skills. Final video interview with our CEO. Ready to apply? Send us your resume along with links to your previous work or GitHub profile. Make sure your application has a link to your Telegram messenger. This is the main way we will try to communicate with you. Відгукнутись на вакансію

Full-time Вчора

Senior Software Engineer

airSlate Kyiv За результатами співбесіди

About AirSlate airSlate is a global SaaS technology company that develops no-code workflow automation, electronic signature, and document management solutions. Our award-winning products - SignNow, pdfFiller, DocHub, altaFlow, Instapage, and US Legal Forms - serve over hundreds of millions of users and more than one million customers worldwide, helping organizations of every size digitize processes, improve efficiency, and transform how they work. We’re in an exciting phase of growth and transformation, with teammates in more than 20 countries across three continents and main hubs in the United States, Poland, Romania, Ukraine and Philippines . At airSlate, we’re building value for customers and a culture where growth and innovation go hand in hand. We’re looking for people eager to shape products, scale a company, and thrive in a fast-moving environment. About USLegal Team We are a passionate and ambitious team of 23 people on a mission to succeed with our largest online library of legal forms - USLegal. Since 1997, US Legal Forms empowers attorneys, small businesses, and even individuals to get their legal documents done. With US Legal Forms, users have access to an online library of more than 85,000 legal templates, detailed guidelines, completion and online notary services. And now, we are looking for a PHP Backend Developer who is prepared to contribute to the next chapter of our company's growth. What You'll Be Working On - Design, build, and maintain backend features and APIs for US Legal Forms using PHP/Laravel Bring an AI-forward approach to daily work - find and implement ways AI can help the team build and ship faster and smarter Contribute cross-functionally when needed, including some React frontend work Analyse A/B test results and own the impact of your work on product outcomes Take part in technical and process decisions, helping the team operate independently with minimal PM involvement Write tested, maintainable code and help uphold quality standards Proactively raise ideas that make the team faster, smarter, and more impactful What We Expect From You - 3+ years of backend development experience Strong PHP/Laravel proficiency Hands-on experience using AI tools to improve real development work Solid experience with REST APIs, SQL/MySQL, message queues (SQS), and cloud/AWS Good testing practices and a commitment to code quality Basic Python knowledge for some tasks Basic knowledge of React for cross-functional contributions Proactive and independent, with a clear sense of ownership; comfortable making decisions in a low-bureaucracy team English level B1+ What We Offer Flexible working environment - Our teams operate across the globe. We value in‑person collaboration in our hubs, but we also embrace remote and hybrid working. You can work from one of our offices in the United States, Poland, Romania or Ukraine, or remotely from many countries. Competitive compensation and stock options - We offer salaries that reflect local market conditions and experience, plus a performance-based bonus system and stock options so you share in the company’s growth. Professional growth and learning - We invest in your development through courses, conferences, and access to learning resources. We encourage career growth and internal mobility, supporting teammates who want to explore new opportunities within airSlate. Health and well‑being - We provide comprehensive benefits tailored to each country, including health coverage, wellness programmes and access to fitness options. We also dedicate quarterly company-wide Mental Health Days, when everyone takes time off to rest and recharge. Family‑friendly culture - Family life is part of who we are, and we embrace it in many forms. From flexibility for parents to our airSlate Junior Club for kids, to company-wide family days and our pet-friendly approach, we’re committed to making work and life easier to balance. Giving back - We support charitable initiatives around the world through the airSlate Care programme. Our current focus includes humanitarian aid in Ukraine and other regions, matching employee donations and supporting causes chosen by our teams. Open communication - We encourage transparent dialogue at all levels. From team discussions to company-wide Q&A sessions with our CEO, we make sure everyone has the chance to be heard and to influence how we grow. It is airSlate's policy to comply with all applicable equal employment opportunity laws by making all employment decisions without unlawful regard or consideration of any individual’s race, religion, ethnicity, color, sex, sexual orientation, gender identity or expressions, transgender status, sexual and other reproductive health decisions, marital status, age, national origin, genetic information, ancestry, citizenship, physical or mental disability, veteran or family status or any other basis protected by applicable national, federal, state, provincial or local law. airSlate's policy prohibits unlawful discrimination based on any of these impermissible bases, as well as any bases or grounds protected by applicable law in each jurisdiction. If you need assistance or an accommodation during the application process because of a disability, it is available upon request. airSlate is pleased to provide such assistance and no applicant will be penalized as a result of such a request. Pursuant to relevant law, where applicable, airSlate will consider for employment qualified applicants with arrest and conviction records. Read our Recruitment Privacy Notice to Learn how we process your personal information. We may use artificial intelligence (AI) tools to support parts of the hiring process, such as reviewing applications, analyzing resumes, or assessing responses and identifying potential inconsistencies or verification signals in application materials based on available information. These tools assist our recruitment team but do not replace human judgment. Final hiring decisions are ultimately made by humans. If you would like more information about how your data is processed, please contact us.

Full-time Вчора

Backend Developer

Readeat Віддалено від $2,500

Requirements 3+ years of commercial software development experience with a strong focus on backend systems. Proficiency in PHP and deep knowledge of the Laravel framework (service providers, eloquent ORM, queues, and optimization). Strong expertise in Node.js and hands-on experience with NestJS for building scalable microservices or monolithic applications. Solid understanding of Next.js, particularly for Full-Stack development, Server-Side Rendering (SSR), and API routes. Proficient in designing, optimizing, and managing relational databases using MySQL and PostgreSQL (indexing, query profiling, and schema design). Hands-on experience with AWS cloud services, including EC2, S3, RDS, Lambda, and basic infrastructure management. Strong understanding of OOP, SOLID principles, architectural patterns, and clean code practices. Experience with containerization using Docker and setting up basic CI/CD pipelines. Familiarity with caching mechanisms and message brokers, such as Redis or RabbitMQ. Strong communication skills and the ability to work effectively in an agile team environment. Responsibilities Developing, maintaining, and optimizing scalable backend services, APIs, and system architecture. Designing efficient database schemas, writing complex queries, and managing data storage performance. Deploying, configuring, and scaling application infrastructure within cloud environments. Collaborating with cross-functional teams to integrate frontend elements with server-side logic. Writing clean, maintainable, and well-tested code in accordance with industry best practices. Participating in code reviews to ensure code quality and share knowledge within the team. Troubleshooting, debugging, and resolving performance bottlenecks and production issues. Integrating third-party services, external APIs, and payment gateways. Implementing and maintaining CI/CD pipelines and containerized development environments. Participating in agile team processes, including sprint planning and task estimation. Intervew steps pre-screen. tech interview. Відгукнутись на вакансію

Пакети за темою

Bagisto

bagisto/bagisto

Bagisto — це платформа для електронної комерції, побудована на Laravel. Вона надає готове рішення для створення та управління інтернет-магазинами з підтримкою каталогу товарів, замовлень, платежів та клієнтів.

27,343 v2.4.6 12 3

Lang

laravel-lang/lang

Список 126 мов для Laravel Framework, Laravel Jetstream, Laravel Fortify, Laravel Breeze, Laravel Cashier, Laravel Nova, Laravel Spark та Laravel UI.

7,779 15.31.4 2