Example of thinkPHP universal controller implementation method

  • 2021-08-16 23:23:56
  • OfStack

This paper describes the implementation method of thinkPHP general controller with examples. Share it for your reference, as follows:


<?php
namespace  Directory \Controller;
class TypeController extends Controller
{
  public function add()
  {
    if(IS_POST)
    {
      $model = D('Type');
      if($model->create())
      {
        if($model->add())
        {
          $this->success(' Add successfully! ', U('lst'));
          exit;
        }
        else
        {
          $sql = $model->getLastSql();
          $this->error(' Failed to insert database! .<hr />SQL:'.$sql);
        }
      }
      else
      {
        $error = $model->getError();
        $this->error($error);
      }
    }
    $this->display();
  }
  public function lst()
  {
    $model = D('Type');
    $data = $model->search();
    $this->assign($data);
    $this->display();
  }
  public function save($id)
  {
    $model = D('Type');
    if(IS_POST)
    {
      if($model->create())
      {
        if($model->save() !== FALSE)
        {
          $this->success(' Modified successfully! ', U('lst'));
          exit;
        }
        else
        {
          $sql = $model->getLastSql();
          $this->error(' Failed to modify database! .<hr />SQL:'.$sql);
        }
      }
      else
      {
        $error = $model->getError();
        $this->error($error);
      }
    }
    $data = $model->find($id);
    $this->assign('data', $data);
    $this->display();
  }
  public function del($id)
  {
    $model = D('Type');
    $model->delete($id);
    $this->success(' Operation successful! ', U('lst'));
  }
  public function bdel()
  {
    $delid = I('post.delid');
    if($delid)
    {
      $delid = implode(',', $delid);
      $model = D('Type');
      $model->delete($delid);
    }
    else
      $this->error(' Please select a record to delete !');
    $this->success(' Operation successful! ', U('lst'));
  }
}

For more readers interested in thinkPHP related contents, please check the topics of this site: "ThinkPHP Introduction Tutorial", "thinkPHP Template Operation Skills Summary", "ThinkPHP Common Methods Summary", "codeigniter Introduction Tutorial", "CI (CodeIgniter) Framework Advanced Tutorial", "Zend FrameWork Framework Introduction Tutorial" and "PHP Template Technology Summary".

Hope that this article is based on the framework of ThinkPHP PHP programming help.


Related articles: