5. Model
ใน Joomla 3 มีส่วนประกอบ Model มีหน้าที่จัดการข้อมูลและโต้ตอบกับฐานข้อมูล โมเดลโดยทั่วไปประกอบด้วยวิธีการเรียกค้น จัดเก็บ ปรับปรุง และลบข้อมูลจากฐานข้อมูล นอกจากนี้ยังมีฟังก์ชันการตรวจสอบและการกรองเพื่อให้แน่ใจว่าข้อมูลถูกป้อนอย่างถูกต้องและตรงตามเกณฑ์ที่กำหนด
5.1 สร้างโฟลเดอร์สำหรับเก็บไฟล์ Model
5.2 สร้างไฟล์ a.php
Code ของไฟล์ models/a.php
<?php
/**
* @package HelloComponent
* @subpackage com_hellocomponent
* @author Mindphp Developer Teams
* @copyright Copyright (C) 2021 Mindphp. All rights reserved..
* @license GNU General Public License version 2 or later;
*/
defined('_JEXEC') or die();
class HellocomponentModelA extends Joomla\CMS\MVC\Model\ListModel
{
function getDate()
{
return date('y:m:d');
}
}
คำอธิบายโค้ด
-
class HellocomponentModelA extends Joomla\CMS\MVC\Model\ListModel
สร้างคลาสชื่อ HellomindphpModelA (ขึ้นต้นด้วย "ชื่อของ Component" ตามด้วยคำว่า "Model" และ "ชื่อของ Model") โดยการสืบทอดคุณสมบัติมาจากคลาส ListModel
-
function getDate() { return date('y:m:d'); }
สร้าง Method ชื่อ getData และส่งค่า "วันที่" กลับคืนให้ Method
5.3 การทำงานระหว่าง View กับ Model
5.3.1 เปิดไฟล์ views/a/view.html.php เพิ่มโค้ด
class HellocomponentViewA extends Joomla\CMS\MVC\View\HtmlView
{
function display($tpl = null)
{
$this->date = $this->get('Date');
echo "Test View A<br/>";
$this->sidebar = JHtmlSidebar::render();
$this->addToolbar();
parent::display($tpl);
}
public function addToolbar()
{
\Joomla\CMS\Toolbar\ToolbarHelper::title(JText::_('COM_HELLOCOMPONENT_A'));
\Joomla\CMS\Toolbar\ToolbarHelper::preferences('com_hellocomponent');
}
}
คำอธิบายโค้ด
-
เรียกใช้งานเมธอด getData() โดยวิธีเรียกใช้คือ $this->get('Date') และให้เก็บในตัวแปล $this->date$this->date = $this->get('Date');
5.3.2 เปิดไฟล์ views/a/tmpl/default.php เพิ่มโค้ด
<p>Test Layoul A</p>
<p><?php echo $this->date; ?></p>