PHP code example of sfneal / view-models

1. Go to this page and download the library: Download sfneal/view-models library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sfneal / view-models example snippets


use Sfneal\ViewModels\ViewModel;

class PostViewModel extends ViewModel
{
    public $indexUrl = null;
   

    public function __construct(User $user, Post $post = null)
    {
        $this->user = $user;
        $this->post = $post;
        
        $this->indexUrl = action([PostsController::class, 'index']);
        $this->view = 'your.view'; 
    }
    
    public function post(): Post
    {
        return $this->post ?? new Post();
    }
    
    public function categories(): Collection
    {
        return Category::canBeUsedBy($this->user)->get();
    }
}

class PostsController
{
    public function create()
    {
        // Uses caching for fast load times after first request
        return (new PostViewModel(current_user()))->render();
    }
    
    public function edit(Post $post)
    {
        // Doesn't use caching to avoid need for cache invalidation on changes
        return (new PostViewModel(current_user(), $post))->renderNoCache();
    }
}