DEV Community

Discussion on: What is the best way to implement a view layer logic?

 
dsazup profile image
Dainius

Actually, you should probably use Htmlable interface, if you want to return html from your 'cell'.

Well lets take a look at this example from CakePHP

namespace App\View\Cell;

use Cake\View\Cell;

class InboxCell extends Cell
{

    public function display()
    {
        $this->loadModel('Messages');
        $unread = $this->Messages->find('unread');
        $this->set('unread_count', $unread->count());
    }
}

What this does, is basically counts how many unread messages there are, and returns a different html template. Now, I don't have messages model in my app, so let's say I want to return a count of how many users my app has. Lets call it UsersCountCell for now.

In my app folder, I create UsersCountCell.php with the following content,

<?php

namespace App;

use Illuminate\Contracts\Support\Htmlable;

class UsersCountCell implements Htmlable
{
    public function toHtml()
    {
        $userCount = User::count();

        return view('cells.users_count', [
            'count' => $userCount,
        ]);
    }
}
//resources/views/cells/users_count.blade.php
<div>
There are {{ $count }} users
</div>

You then use it like this:

Route::get('/', function () {
    return view('welcome', [
        'cell' => new \App\UsersCountCell(),
    ]);
}); 
//resources/views/welcome.blade.php
<div>
    The following will come from htmlable: {{ $cell}}
</div>

This will properly render the html from your users_count.blade.php, whereas previously mentioned renderable would require you to render it like this {!! $cell !!}. You can actually use both interfaces, and then in your toHtml() method just return $this->render();

Let me know if you need any more information, I might write a blog post about this 🤔

Thread Thread
 
msamgan profile image
Mohammed Samgan Khan

thanks a lot.
I guess I can work on this. thanks a lot and I will be waiting for the article...
:P