Задание №4 Разработка сайта с использованием mvc фреймворка
Цель работы: получить практические навыки разработки модулей приложений с помощью Фреймворка CodeIgniter.
Задание к работе:
Ознакомиться с теоретическим материалом.
Создать приложение согласно варианту (использовать элементы из таблицы 1 первого задания)
Разработать структуру приложения
Создать скрипт на php для ввода и выдачи результата, используя MVC
Оформить отчет согласно требованиям.
Ход работы:
Первым действием будет создание универсальной crud модели от которой будет наследоваться наша модель “equipment”. Листинг модели приведен ниже:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Crud extends CI_Model{
var $table = '';
var $add_rules = array();
var $edit_rules = array ();
function crud(){
parent::__construct();
}
function getlist(){
$query = $this->db->get($this->table);
$res = $query->result_array();
return $res;
}
function add(){
$this->form_validation->set_rules($this->add_rules);
if ($this->form_validation->run()){
$data = array();
foreach ($this->add_rules as $each){
$field = $each['field'];
$data[$field] = $this->input->post($field);
}
$this->db->insert($this->table,$data);
return $this->db->insert_id();
}
else{
return false;
}
}
function update($id){
$this->form_validation->set_rules($this->edit_rules);
if ($this->form_validation->run()){
$object = array();
foreach ($this->edit_rules as $each){
$field = $each['field'];
$object[$field] = $this->input->post($field);
}
$this->db->where('id',$id);
$this->db->update($this->table,$object);
return $this->db->insert_id();
}
else{
return false;
}
}
function delete($id){
$this->db->where('id',$id);
$this->db->delete($this->table);
}
function show($id){
$this->db->where('id', $id);
$query = $this->db->get($this->table);
return $query->row_array();
}
}
?>
Далее создадим непосредственно модель “equipment” и унаследуем ее от CRUD модели:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Mdl_equipment extends crud{
var $table = 'equipment';
var $add_rules = array(
array(
'field' => 'full_name',
'label' => 'name',
'rules' => 'required'
),
array(
'field' => 'type',
'label' => 'test description',
'rules' => 'required'
)
);
var $edit_rules = array (
array(
'field' => 'full_name',
'label' => 'name',
'rules' => 'required'
),
array(
'field' => 'type',
'label' => 'test description',
'rules' => 'required'
)
);
function mdl_equipment(){
parent::__construct();
}
}
?>
Здесь мы задаем правила валидации и название рабочей таблицы в БД. Все остальное реализовано в CRUD библиотеке.
Создадим контроллер со всеми необходимыми операциями добавления/редактирования/удаления
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Equipment extends CI_Controller{
var $table = 'equipment';
function equipment(){
parent::__construct();
$this->load->model('mdl_equipment');
}
public function index(){
render('equipment/index','all equipment');
}
function show($id){
$data = $this->mdl_equipment->show($id);
render('equipment/show','show equipment', $data);
}
public function add(){
if ($this->mdl_equipment->add() !== false){
redirect('index.php/' . $this->table . '/index');
}
else{
render($this->table . '/add','create equipment');
}
}
public function edit($id){
$this->db->where('id',$id);
$request = $this->db->get($this->table);
$object = $request->row_array();
if ($this->mdl_equipment->update($id) !== false){
redirect('index.php/equipment/index');
}
else{
render('equipment/edit','edit equipment', $object);
}
}
public function delete($id){
$this->mdl_equipment->delete($id);
redirect('index.php/' . $this->table . '/index');
}
}
?>
Также создадим view файлы:
Add.php (Edit.php практически аналогичен):
<h1 class="page_title">Add equipment</h1>
<?php echo validation_errors(); ?>
<?= form_open('/index.php/equipment/add') ?>
<?
$options = array(
'computer' => 'computer',
'tablet' => 'tablet'
);
?>
<p class="form_labels">Equipment type: </p>
<?= form_dropdown('type', $options, 'mdl_test_classic'); ?>
<p class="form_labels">Name: </p>
<?= form_input(array('name' => 'full_name', 'class' => 'input_fields' )) ?>
<?= form_submit(array('class' => 'buttons', 'value' => 'Add equipment', 'class' => 'buttons')); ?>
<?= form_close() ?>
Index.php:
<h1 class="page_title">Test list</h1>
<table align="center" width="100%" border="1" class="tables">
<thead>
<tr>
<td>Id
<td>Type
<td>Name
<td>Delete
</tr>
</thead>
<tbody>
<?php
$list = $this->mdl_equipment->getlist();
$size = count($list);?>
<?foreach ($list as $each):?>
<tr onclick="window.location = '<?= base_url() . 'index.php/equipment/edit/' . $each['id']; ?>'">
<td> <?=$each['id'];?>
<td> <?=anchor('index.php/tests/show/' . $each['id'], $each['type']);?>
<td> <?=$each['full_name'];?>
<td> <?=anchor('index.php/equipment/delete/' . $each['id'],'delete',array('class' => 'crud_links'));?>
<?endforeach?>
</tbody>
</table>
<input type="button" class="buttons" value="Add test" onclick="document.location='<?= base_url() . 'index.php/equipment/add' ?>'" />
В итоге получим следующее CRUD приложение:
Основная форма со списком оборудования.
Форма для добавления(аналогично для редактирования)