Composers, also sometimes called View Composers, are essentially identical to the Laravel system of the same name. They allow you to pass data to views (blade templates), scoping that data to that view (and any views it subsequently includes). If you're familiar with Sage 9's data filters, or the Controller package often used with Sage 9, then Composers are a similar concept, but much more powerful: Instead of only allowing data binding to top-level WordPress templates, Composers allow you target any view.
Composers are autoloaded, which means their naming needs to conform to the PSR-4 standard.
If you're using WP-CLI, you can create composers from the command line:
This would create a Composer called
If you're not using WP-CLI, the most basic Composer looks like this:
This composer doesn't do anything yet, though, so let's give it some functionality.
Because that variable is scoped to
example.blade.php, we'll also see the following behavior:
We've seen how data can be bound to views, but we only returned a hard-coded string. Usually you'll want something more involved than that.
Composers are executed in a context where WordPress functions like
the_post() will return expected values, so you can retrieve data from WordPress much like you normally would.
Inside of a Composer, you can easily access data that has been passed to or inherited by the view through the
"Automatic" view selection
You can always define what view a Composer will be bound to using the
$views property to list the name(s) of the views.
However, if your Composer will target only a single view, you can save yourself a few lines of code.
Sage will attempt to match Composers to views based on some simple file path logic:
If your view and Composer share the same path segments and name, they'll be automatically bound together.
For example, if your view is a partial at
/resources/views/partials/page-header.blade.php, a Composer at
/app/View/Composers/PageHeader.php will be automatically bound to it.
In other words:
- Match paths below
- Convert the
kebab-caseof view file names to the
with() used above to pass data to views, but it has a more aggressive sibling calling
override() which does the same thing--except that it will replace data inherited by, or passed to, the view while
with() will not.
Help us continue to build and maintain our open source projects. We’re a small team of independent developers and every little bit helps.Sponsor Roots on GitHub