Laravel Composable View Composers Package - Compose View Composers from Component Composers

Related tags

Laravel virtuoso
Overview

image

Laravel Virtuoso

Laravel Composable View Composers Package

Increase flexibility and reduce code duplication by easily composing complex View Composers from simple component Composers without unnecessary indirection or boilerplate code.

Background

In many of our projects, the same data is often repeated on multiple pages. This presents the challenge of preparing this data in our Controllers and providing it to our various Views without an undue amount of code repetition. Laravel provides us with the ability to limit this potential repetition through an abstraction known as the View Composer. A View Composer allows you to abstract this code to a single location and make it available to multiple Views. A View Composer is simply a piece of code which is bound to a View and executed whenever that View is requested.

An example View Composer from the Laravel documentation:

View::composer('profile', function($view)
{
	$view->with('count', User::count());
}

A View Composer may also be created as a Class:

<?php namespace My\Project\Name\Space;

class UserCountComposer
{

	public function compose($view)
	{
		$view->with('count', User::count());
	}

}

Of course, when a View Composer is created as a Class, the association between the View Composer and the View must be registered, either using the following syntax:

View::composer('profile', 'UserCountComposer');

or via a Service Provider:

<?php namespace My\Project\Name\Space;
 
use Illuminate\Support\ServiceProvider;
 
class ComposerServiceProvider 
	extends ServiceProvider 
{
 
	public function register()
  	{
    	$this->app['view']->composer('profile', 'My\Project\Name\Space\UserCountComposer');
  	}
 
}

Data provided to the View by a View Composer may be accessed as if it had been provided by the Controller:

<ul>
	@foreach ($data as $datum)
		<li>{{ $datum }}</li>
	@endforeach
</ul>

Additional Resources

Application

Unfortunately, the out-of-the-box functionality of Laravel View Composers can be somewhat cumbersome.

If we choose to go with the View::composer() format, our bootstrap files will quickly become overblown and unwieldy. On the other hand, if we choose a Class based approach, in addition to creating the View Composer Classes, we need to register our Composer/View associations. This presents its own challenges. We might choose to create a Service Provider to register each of our Composer/View associations, resulting in repetitive boilerplate code as our Service Providers proliferate. Alternately, we might choose to create a single Service Provider to register all of our Composer/View associations, but this merely simplifies our bootstrap files at the expense of an unwieldy Service Provider. Perhaps the best choice is to create a Service Provider for each View and within it register its View Composer associations, but this requires a fair amount of boilerplate and dramatically increases the indirection which already exists with View Composers.

This is the challenge that Virtuoso is intended to meet. Virtuoso allows you to easily create simple, single-focused View Composers for your data and leverage composition when providing data to your Views by associating one or more View Composers with a single View via a "Composite Composer" as needed without any unnecessary indirection or repetitive boilerplate code - all of your Composer/View associations can be found in a single location and all without writing any new Service Providers!

Requirements

Virtuoso supports the following versions of PHP:

  • PHP 5.4.*
  • PHP 5.5.*
  • PHP 5.6.*
  • HHVM

and the following versions of Laravel:

  • Laravel 4.1.*
  • Laravel 4.2.*

Installation

First, install Virtuoso through Composer (Virtuoso on Packagist), either by adding it to the Require Array of your composer.json:

"require": {
    "coderabbi/virtuoso": "0.*"
}

or from the Command Line:

php composer.phar require coderabbi/virtuoso:0.*

Next, update app/config/app.php to include a reference to this package's Service Provider in the Providers Array:

'providers' => array(
    'Coderabbi\Virtuoso\ComposerServiceProvider'
)

Finally, update app\config\view.php to include the Composers Array:

'composers' => array (
)

Usage

Simple View Composers

First, create your View Composer as you normally would (make sure to implement the Composer Interface):

<?php namespace My\Project\Name\Space;

use Coderabbi\Virtuoso\Composer;

class MyFirstSimpleComposer
	implements Composer
{

	public function compose($view)
	{
		$view->with('myData', $this->getMyData());
	}
	
	private function getMyData()
	{
		// do your thing here
	}
	
}

Ideally, you should limit the data provided by each Composer to it's simplest, most cohesive unit. This will allow you to compose Composite View Composers for your Views more easily.

Next, associate the View (full path within the View Directory specified in app/config/view.php using dot notation) with your Simple View Composer (fully qualified Class Name including Namespace) by adding it to the Composers Array in app\config\view.php:

'composers' => array (
	'partials.header' => 'My\Project\Name\Space\MyFirstSimpleComposer',
)

That's it! Virtuoso will take care of registering the View/Composer associations for you - no new Service Providers required!

You may access data provided by the Simple View Composer from the View as you normally would.

Composite View Composers

First, create the simple View Composers which will together comprise the Composite View Composer as above (but do not associate them with your View in the Composer Array in app\config\view.php).

Next, create your Composite View Composer (make sure to extend CompositeComposer) and add the component View Composers to its $composers array:

<?php namespace My\Project\Name\Space;

use Coderabbi\Virtuoso\CompositeComposer;

class MyFirstCompositeComposer
	extends CompositeComposer
{

	protected $composers = array(
		'MyFirstSimpleComposer',
		'MySecondSimpleComposer',
		'MyThirdSimpleComposer'
	);
	
}

Finally, associate your Composite View Composer (fully qualified Class Name including Namespace) with the View (full path within the View Directory specified in app/config/view.php using dot notation) by adding it to the Composers Array in app\config\view.php:

'composers' => array (
	'partials.header' => 'My\Project\Name\Space\MyFirstCompositeComposer',
)

That's it! Virtuoso will take care of registering the individual View/Composer associations for you - no new Service Providers Required!

You may access data provided by the Composite View Composer from the View as you normally would.

Roadmap

The addition of tests will bring the package to v1.0. It's a very simple package designed to address a single limitation in the standard implementations of Laravel View Composers so at this time I have no further plans for the package beyond that version. You are welcome to submit Issues or Pull Requests if you are so inclined; I will give my full attention to each.

License

This package is open-sourced software licensed under the MIT license. Further details may be found in the LICENSE file.

Author

Follow @coderabbi on Twitter.

You might also like...
A simple `make:view` command for Laravel applications.

A simple make:view command for Laravel applications. Quickly generate a new Blade view from the console using artisan make:view. Installation You can

Dashboard to view your http client requests in laravel application
Dashboard to view your http client requests in laravel application

Laravel Blanket is a package with wraps laravel http client requests and provide logs for request and response, also give option to retry any request from dashboard and more...

View your Laravel routes on the browser.
View your Laravel routes on the browser.

View your Laravel routes on the browser. This package adds a route to your Laravel application. Once you've installed this package, enter /route-list

Is an Extension of Laravel View Class which compiles String Template on the fly. It automatically detects changes on your string template and recompiles it if needed.

Laravel-fly-view Is an Extension of Laravel View Class which compiles String Template on the fly. It automatically detects changes on your string temp

View template engine of PHP extracted from Laravel

Blade 【简体中文】 This is a view templating engine which is extracted from Laravel. It's independent without relying on Laravel's Container or any others.

Filament-spatie-laravel-activitylog - View your activity logs inside of Filament. ⚡️

View your activity logs inside of Filament. This package provides a Filament resource that shows you all of the activity logs created using the spatie

Laravel Livewire full page component routing.

Laravel Livewire Routes Laravel Livewire full page component routing. This package allows you to specify routes directly inside your full page Livewir

Laravel Livewire form component with declarative Bootstrap 5 fields and buttons.

Laravel Livewire Forms Laravel Livewire form component with declarative Bootstrap 5 fields and buttons. Requirements Bootstrap 5 Installation composer

Laravel component to create gorgeous Charts.css charts.
Laravel component to create gorgeous Charts.css charts.

Laravel component to create gorgeous Charts.css charts. This package will help you generate CSS only charts based on the Charts.css library. Installat

Comments
Releases(v0.9.4)
Owner
Yitzchok Willroth
Coder & Rabbi, mostly async; Startup Vet, DevCamp Guide, Mentor, Consultant, Speaker, Author; ShorePHP Founder, NYPHP Organizer
Yitzchok Willroth
View themes is a simple package to provide themed view support to Laravel.

Laravel View Themes View themes is a simple package to provide themed view support to Laravel. Installation Add alexwhitman/view-themes to the require

Alex Whitman 15 Nov 29, 2022
Jetstrap is a lightweight laravel 8 package that focuses on the VIEW side of Jetstream / Breeze package installed in your Laravel application

A Laravel 8 package to easily switch TailwindCSS resources generated by Laravel Jetstream and Breeze to Bootstrap 4.

null 686 Dec 28, 2022
Testbench Component is the de-facto package that has been designed to help you write tests for your Laravel package

Laravel Testing Helper for Packages Development Testbench Component is the de-facto package that has been designed to help you write tests for your La

Orchestra Platform 1.9k Dec 29, 2022
Stash view is a composer package for Laravel which caches views using Russian Doll Caching methodology.

Stash View Stash view is a composer package for Laravel which caches views using Russian Doll Caching methodology. What is Russian Doll Caching ? It i

Bhushan Gaikwad 18 Nov 20, 2022
27Laracurl Laravel wrapper package for PHP cURL class that provides OOP interface to cURL. [10/27/2015] View Details

Laracurl Laravel cURL Wrapper for Andreas Lutro's OOP cURL Class Installation To install the package, simply add the following to your Laravel install

zjango 8 Sep 9, 2018
This package provides a Logs page that allows you to view your Laravel log files in a simple UI

A simplistics log viewer for your Filament apps. This package provides a Logs page that allows you to view your Laravel log files in a simple UI. Inst

Ryan Chandler 9 Sep 17, 2022
A package that adds view-composer like feature to Inertia.js Laravel adapter

Kinetic A package that adds view-composer like feature to Inertia.js Laravel adapter. Use to be able to share props based on the Inertia component nam

Marvin Quezon 76 Dec 12, 2022
This package provides a Filament resource to view all Laravel sent emails.

This package provides a Filament resource to view all Laravel outgoing emails. It also provides a Model for the database stored emails. Installation Y

Ramón E. Zayas 22 Jan 2, 2023
A package that helps to group methods that mostly use for the view presentation purpose.

A package that helps to group methods that mostly use for the view presentation purpose form models to a dedicated presenter class.

Touhidur Rahman 9 Apr 26, 2022
This package allows you to render livewire components like a blade component, giving it attributes, slots etc

X-livewire This package allows you to render livewire components like a blade component, giving it attributes, slots etc. Assuming you wanted to creat

null 7 Nov 15, 2022