再次用CodeIgniter實現簡易blog

 

  天變冷了,人也變得懶了很多,因爲工做的須要,最近一直在學習CodeIgniterCI)框架的使用,沒有系統的從PHP基本語法學起,在網上靠百度谷歌,東拼西湊的實現了一些簡單的功能。因此,老PHPer能夠繞道了。javascript

PHP實現簡易blog

  參考該篇博客所實現的功能,從新用CI實現了一下。php

  主要實現文章的添加、查看、刪除、搜索。這裏面最難實現的是文章分頁,看似簡單的功能,卻費了一些功夫。css

固然,離一個完整的系統還有不少功能沒開發,這裏只是簡單引用了bootstrap的樣式。html

 

 

MVC模型                         前端

 

CI遵循於MVC模型,若是接觸過其它基於MVC模型的web框架的話,理解起來仍是比較簡單的。java

 

    web的開發主要就是在這三個目錄下進行。mysql

  • 控制器(controllers目錄) 是模型、視圖以及其餘任何處理 HTTP 請求所必須的資源之間的中介,並生成網頁。
  • 模型(models目錄) 表明你的數據結構。一般來講,模型類將包含幫助你對數據庫進行增刪改查的方法。
  • 視圖(views目錄) 是要展示給用戶的信息。一個視圖一般就是一個網頁,可是在 CodeIgniter 中, 一個視圖也能夠是一部分頁面(例如頁頭、頁尾),它也能夠是一個 RSS 頁面, 或其餘任何類型的頁面。

 

注:本文中的CI運行基於WAMPServer 環境。jquery

 

 

建立模型                                                           git

打開phpMyAdmin建立表。github

 

這裏主要基於該表設計,表名爲「myblog」。

在.../application/config/database.php 添加數據庫鏈接。

mysql默認密碼爲空,數據庫名爲「test」。「myblog」表在「test」庫下建立。

 

下面實現數據模型層代碼,主要是以CI的規則來操做數據庫。

.../application/models/News_model.php

<?php
class News_model extends CI_Model {
    public function __construct()
    {
        $this->load->database();
    }
    //獲取全部blog
    public function blogs($w,$num,$offset)
    {    
        
        
        if($w == 1)
        {    
            $query = $this->db->get('myblog',$num,$offset);
            return $query->result_array();
        
        }elseif(strpos($w,"title like"))
        {
            $query = $this->db->query("select * from myblog where $w order by id desc limit 5;");
            return $query->result_array();
        
        }else{
        
            $query = $this->db->get('myblog',$num,$offset);
            return $query->result_array();
            
        }
        
    }
    
    //查看一篇blog
    public function up_blogs($id = FALSE)
    {
        if ($id === FALSE)
        {
            $query = $this->db->get('myblog');
            return $query->result_array();
        }
        //更新點擊數
        $this->db->query("update myblog set hits=hits+1 where id='$id';");
        $query = $this->db->get_where('myblog', array('id' => $id));
        return $query->row_array();
    }
    
    //添加一篇blog
    public function add_blogs()
    {
        $this->load->helper('url');
        //$slug = url_title($this->input->post('title'), 'dash', TRUE);
        $d = date("Y-m-d");
        $data = array(
            'title' => $this->input->post('title'),
            'dates' => $d,
            'contents' => $this->input->post('text')
        );
        return $this->db->insert('myblog', $data);
    }
    //刪除一篇blog
    public function del_blogs($id = FALSE){
        
        $this->load->helper('url');
        
        if ($id === FALSE)
        {
            $query = $this->db->get('myblog');
            return $query->result_array();
        }
        $array = array(
            'id' => $id
        );
        return $this->db->delete("myblog",$array);
        
    }
}

 

 

建立控制                                                        

控制層一直起着承前啓後的做用,前是前端頁面,後是後端數據庫。

.../application/controllers/News.php

<?php
class News extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
        $this->load->model('news_model');
        $this->load->helper('url_helper');
    }
    public function index()
    {
        $this->load->library('calendar'); //加載日曆類
        parse_str($_SERVER['QUERY_STRING'], $_GET);
        $this->load->library('pagination');//加載分頁類
        $this->load->model('news_model');//加載books模型
        $res = $this->db->get('myblog');//進行一次查詢            
        $config['base_url'] = base_url().'index.php/news/index';//設置分頁的url路徑              
        $config['total_rows'] = $res->num_rows();//獲得數據庫中的記錄的總條數             
        $config['per_page'] = '3';//每頁記錄數
        $config['prev_link'] = 'Previous ';
        $config['next_link'] = ' Next';
        
        $this->pagination->initialize($config);//分頁的初始化
        
        if (!empty($_GET['key'])) {
            $key = $_GET['key'];
            $w = " title like '%$key%'";
            
        }else{
            $w=1;
            
        }
        
        $data['blogs'] = $this->news_model->blogs($w,$config['per_page'],$this->uri->segment(3));//獲得數據庫記錄
        
        $this->load->view('templates/header');
        $this->load->view('news/index', $data);
        $this->load->view('templates/footer');
        
    }
    public function view($id = NULL)
    {
        $this->load->library('calendar'); 
        $data['blogs_item'] = $this->news_model->up_blogs($id);
        if (empty($data['blogs_item']))
        {
            show_404();
        }
        $data['title'] = $data['blogs_item']['title'];
        
        $this->load->view('templates/header');
        $this->load->view('./news/view', $data);
        $this->load->view('templates/footer');
    }
    
    public function del($id = NULL)
    {
        $this->news_model->del_blogs($id);
        //經過js跳回原頁面
        echo'
            <script language="javascript"> 
                alert("create success!"); 
                window.location.href="http://localhost/CI_blog/index.php/news/"; 
            </script> ';        
    }
    
    public function create()
    {
        $this->load->library('calendar'); //加載日曆類
        
        $this->load->helper('form');
        $this->load->library('form_validation');
        $data['title'] = 'Create a news item';
        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('text', 'Text', 'required');
        if ($this->form_validation->run() === FALSE)
        {
            $this->load->view('templates/header', $data);
            $this->load->view('news/create');
            $this->load->view('templates/footer');
        }
        else
        {
            $this->news_model->add_blogs();
            
            //跳回blog添加頁面
            echo'
            <script language="javascript"> 
                alert("create success!"); 
                window.location.href="http://localhost/CI_blog/index.php/news/create"; 
            </script> ';
            
        }
        
    }

}

 

 

 

建立視圖                                                         

爲了讓頁面好看,使用了bootstrap。

 

定義頁頭:

.../application/views/templates/header.php

<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3個meta標籤*必須*放在最前面,任何其餘內容都*必須*跟隨其後! -->
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Blog Template for Bootstrap</title>

    <!-- Bootstrap core CSS -->
    <link href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">

    <link href="//v3.bootcss.com/examples/blog/blog.css" rel="stylesheet">

    <script src="//v3.bootcss.com/assets/js/ie-emulation-modes-warning.js"></script>
    
  </head>
View Code

 

定義頁尾:

.../application/views/templates/footer.php

 <footer class="blog-footer">
      <p>Blog template built for <a href="http://getbootstrap.com">Bootstrap</a> by <a href="https://twitter.com/mdo">@mdo</a>.</p>
      <p>
        <a href="#">Back to top</a>
      </p>
    </footer>


    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
    <script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script src="//v3.bootcss.com/assets/js/ie10-viewport-bug-workaround.js"></script>
  </body>
</html>
View Code

 不過,這裏使用的bootstrap並不是引用的本地。而是使用的CDN加速點。

 

blog首頁

.../application/views/news/index.php

<body>

    <div class="blog-masthead">
      <div class="container">
        <nav class="blog-nav">
          <a class="blog-nav-item active" href="#">Blog</a>
          <a class="blog-nav-item" href="//localhost/CI_blog/index.php/news/create">Create</a>
          <a class="blog-nav-item" href="#">Press</a>
          <a class="blog-nav-item" href="#">New hires</a>
          <a class="blog-nav-item" href="//localhost/CI_blog/index.php/login">Login</a>
      <form class="navbar-form navbar-right" method="get">
            <div class="form-group">
              <input type="text" name="key" placeholder="sreach" class="form-control">
            </div>
            <button type="submit" class="btn btn-success">Srecch</button>
          </form>

    
        </nav>
      </div>
    </div>

    <div class="container">

      <div class="row">

        <div class="col-sm-8 blog-main">

          <div class="blog-post">
        <br>
      
          <?php foreach ($blogs as $blogs_item): ?>

        <h2 class="blog-post-title"><?php echo $blogs_item['title']; ?></h2>
        
        <p class="blog-post-meta">
          <?php echo $blogs_item['dates']; ?>
          Reading:<?php echo $blogs_item['hits']; ?></a>
        </p>
        
        <div class="main">
          <?php echo iconv_substr($blogs_item['contents'],0,100); ?>...
        </div>
        <p><a href="<?php echo site_url('news/view/'.$blogs_item['id']); ?>">View article</a></p>
        <p><a href="<?php echo site_url('news/del/'.$blogs_item['id']); ?>">Delete</a></p>
      
        <?php endforeach; ?>
        <!--翻頁連接-->
        <br><br><?php echo $this->pagination->create_links();?>
            
          </div><!-- /.blog-post -->
    
        </div><!-- /.blog-main -->

        <div class="col-sm-3 col-sm-offset-1 blog-sidebar">
          <div class="sidebar-module sidebar-module-inset">
            <h4>About</h4>
            <p>Etiam porta <em>sem malesuada magna</em> mollis euismod. Cras mattis consectetur purus sit amet fermentum. Aenean lacinia bibendum nulla sed consectetur.</p>
          </div>
      <div class="sidebar-module sidebar-module-inset">
            <?php echo $this->calendar->generate(); ?>
          </div>
          <div class="sidebar-module">
            <h4>Archives</h4>
            <ol class="list-unstyled">
              <li><a href="#">March 2014</a></li>
              <li><a href="#">February 2014</a></li>
              <li><a href="#">January 2014</a></li>
              <li><a href="#">December 2013</a></li>
              <li><a href="#">November 2013</a></li>
              <li><a href="#">October 2013</a></li>
              <li><a href="#">September 2013</a></li>
              <li><a href="#">August 2013</a></li>
              <li><a href="#">July 2013</a></li>
              <li><a href="#">June 2013</a></li>
              <li><a href="#">May 2013</a></li>
              <li><a href="#">April 2013</a></li>
            </ol>
          </div>
          <div class="sidebar-module">
            <h4>Elsewhere</h4>
            <ol class="list-unstyled">
              <li><a href="#">GitHub</a></li>
              <li><a href="#">Twitter</a></li>
              <li><a href="#">Facebook</a></li>
            </ol>
          </div>
        </div><!-- /.blog-sidebar -->

      </div><!-- /.row -->

    </div><!-- /.container -->
View Code

 

blog添加頁面

.../application/views/news/create.php

<!-- ckeditor編輯器源碼文件 -->
  <script src="//cdn.ckeditor.com/4.5.5/standard/ckeditor.js"></script>
<body>

    <div class="blog-masthead">
      <div class="container">
        <nav class="blog-nav">
          <a class="blog-nav-item" href="//localhost/CI_blog/index.php/news">Blog</a>
          <a class="blog-nav-item active" href="#">Create</a>
          <a class="blog-nav-item" href="#">Press</a>
          <a class="blog-nav-item" href="#">New hires</a>
          <a class="blog-nav-item" href="#">About</a>
        </nav>
      </div>
    </div>


    <div class="container">

      <div class="blog-header">
        <h2 class="blog-title"><?php echo $title; ?></h2>
        <p class="lead blog-description">Please add an article.</p>
      </div>
  
      <div class="row">

        <div class="col-sm-8 blog-main">

          <div class="blog-post">
      

      <?php echo validation_errors(); ?>

      <?php echo form_open('news/create'); ?>

        <label for="title">Title</label><br/>
        <input type="input" name="title" /><br/>

        <label for="text">Contents</label><br/>
        <textarea rows="10" cols="80" name="text"></textarea><br/>
        <script type="text/javascript">CKEDITOR.replace('text');</script>

        <input type="submit" name="submit" value="Create news item" />

      </form>
  
          </div><!-- /.blog-post -->
      
        </div><!-- /.blog-main -->

        <div class="col-sm-3 col-sm-offset-1 blog-sidebar">
          <div class="sidebar-module sidebar-module-inset">
            <h4>About</h4>
            <p>Etiam porta <em>sem malesuada magna</em> mollis euismod. Cras mattis consectetur purus sit amet fermentum. Aenean lacinia bibendum nulla sed consectetur.</p>
          </div>
      <div class="sidebar-module sidebar-module-inset">
            <?php echo $this->calendar->generate(); ?>
          </div>
          <div class="sidebar-module">
            <h4>Archives</h4>
            <ol class="list-unstyled">
              <li><a href="#">March 2014</a></li>
              <li><a href="#">February 2014</a></li>
              <li><a href="#">January 2014</a></li>
              <li><a href="#">December 2013</a></li>
              <li><a href="#">November 2013</a></li>
              <li><a href="#">October 2013</a></li>
              <li><a href="#">September 2013</a></li>
              <li><a href="#">August 2013</a></li>
              <li><a href="#">July 2013</a></li>
              <li><a href="#">June 2013</a></li>
              <li><a href="#">May 2013</a></li>
              <li><a href="#">April 2013</a></li>
            </ol>
          </div>
          <div class="sidebar-module">
            <h4>Elsewhere</h4>
            <ol class="list-unstyled">
              <li><a href="#">GitHub</a></li>
              <li><a href="#">Twitter</a></li>
              <li><a href="#">Facebook</a></li>
            </ol>
          </div>
        </div><!-- /.blog-sidebar -->

      </div><!-- /.row -->

    </div><!-- /.container -->
View Code

這裏使用了ckeditor 編輯器的使用咱們能夠建立帶格式的文章。一樣引的CDN。

 

最後,還要在routes.php文件中添加如下配置。

.../application/config/routes.php

$route['news/create'] = 'news/create';
$route['news/view'] = 'news/view/$1';
$route['news/del'] = 'news/del/$1';
$route['news/news'] = 'news';
$route['news'] = 'news';
$route['default_controller'] = 'pages/view';

 

好了,主要代碼就這些了。感興趣去github上看完整代碼吧!

https://github.com/defnngj/ci_blog

 

PS:這只是爲了練習而已,因此,各個功能很亂,並沒有打算寫一個完整的系統。

相關文章
相關標籤/搜索