class Post
{
private $id;
private $title;
private $content;
private $author;
public function __construct($id, $title, $content, $author)
{
$this-id = $id;
$this-title = $title;
$this-content = $content;
$this-author = $author;
}
// Getters and Setters
public function getId() { return $this-id; }
public function getTitle() { return $this-title; }
public function getContent() { return $this-content; }
public function getAuthor() { return $this-author; }
public function setTitle($title) { $this-title = $title; }
public function setContent($content) { $this-content = $content; }
}
Step 2: ViewModel 层(PostViewModel.php)
php
<?php
namespace App\ViewModel;
use App\Model\Post;
class PostViewModel
{
private $post;
public function __construct(Post $post)
{
$this-post = $post;
}
public function getDisplayTitle()
{
return strtoupper($this-post-getTitle());
}
public function getShortContent()
{
return substr($this-post-getContent(), 0, 100) 、'...';
}
public function getAuthorInfo()
{
return Written by: {$this-post-getAuthor()};
}
public function getData()
{
return [
'title' = $this-getDisplayTitle(),
'content' = $this-getShortContent(),
'author_info' = $this-getAuthorInfo(),
];
}
}