// Set the value of a variable in the view $messages = [ 'welcome' => 'Welcome to our website!', 'thanks' => 'Thank you for visiting.', ]; View::set('messages', $messages); // Retrieve the value of the 'welcome' message $welcomeMessage = View::get('messages.welcome'); echo $welcomeMessage; // Output: "Welcome to our website!"
// Set the value of a variable in the view $productList = [ 'product1' => 'Product 1', 'product2' => 'Product 2', 'product3' => 'Product 3', ]; View::set('productList', $productList); // Include a partial view file and retrieve a value from it $partialHtml = View::make('partial.product-list')->render(); $selectedProduct = View::get('selectedProduct', '', 'partial.product-list'); echo $partialHtml; // Output: HTML code for the product list echo $selectedProduct; // Output: ""
class ProductViewModel { private $id; private $name; private $price; public function __construct($id, $name, $price) { $this->id = $id; $this->name = $name; $this->price = $price; } public function getId() { return $this->id; } public function getName() { return $this->name; } public function getPrice() { return $this->price; } } // Create a view model object and set it as the view data $product = new ProductViewModel(123, 'Product 1', 9.99); View::setData(['product' => $product]); // Retrieve the value of a variable from the view model $productName = View::get('product')->getName(); echo $productName; // Output: "Product 1"In this example, we create a view model object called `ProductViewModel` that contains the data for a product. We then set this object as the view data using the `View::setData` function. Finally, we retrieve the name of the product from the view model using the `View::get` function. Package library: This example does not use any specific package library, but demonstrates a general programming pattern for creating and using view model objects to organize data for a view.