Using composer with view() helper function

In order to show custom data in the admin of my WordPress website, I have the following action:

add_action('admin_menu', function() {
    add_menu_page( 'Events', 
        'Events', 
        'manage_options', 
        'events', 
        function () {
            echo view('admin.events');
        },
        'dashicons-tickets-alt', 
        6);
});

The view renders properly, but I was trying to use a Composer (class AdminEvents) to pass data to the view, but it does not seem to work. I know I can add a second array to the view() helper function to pass the data, but is there a way to use a composer with a view in this way?

Perhaps something like this?

class AdminEventsComposer {
    public function compose() {
        return [
            'events' => Event::all(),
        ];
    }
}
add_action('admin_menu', function() {
    add_menu_page(
        'Events',
        'Events',
        'manage_options',
        'events',
        function () {
            $composer = new AdminEventsComposer();
            $data = $composer->compose();
            echo view('admin.events', $data);
        },
        'dashicons-tickets-alt',
        6
    );
});
<h1>Events</h1>
<ul>
    @foreach ($events as $event)
        <li>{{ $event->name }}</li>
    @endforeach
</ul>
3 Likes

That technique works. It doesn’t use the Composer structure built into Sage, but will produce a very similar result.

1 Like