zoukankan      html  css  js  c++  java
  • 再次用CodeIgniter实现简易blog

      天变冷了,人也变得懒了不少,由于工作的需要,最近一直在学习CodeIgniterCI)框架的使用,没有系统的从PHP基本语法学起,在网上靠百度谷歌,东拼西凑的实现了一些简单的功能。所以,老PHPer可以绕道了。

    PHP实现简易blog

      参考该篇博客所实现的功能,重新用CI实现了一下。

      主要实现文章的添加、查看、删除、搜索。这里面最难实现的是文章分页,看似简单的功能,却费了一些功夫。

    当然,离一个完整的系统还有很多功能没开发,这里只是简单引用了bootstrap的样式。

    MVC模型                         

    CI遵循于MVC模型,如果接触过其它基于MVC模型的web框架的话,理解起来还是比较简单的。

        web的开发主要就是在这三个目录下进行。

    • 控制器(controllers目录) 是模型、视图以及其他任何处理 HTTP 请求所必须的资源之间的中介,并生成网页。
    • 模型(models目录) 代表你的数据结构。通常来说,模型类将包含帮助你对数据库进行增删改查的方法。
    • 视图(views目录) 是要展现给用户的信息。一个视图通常就是一个网页,但是在 CodeIgniter 中, 一个视图也可以是一部分页面(例如页头、页尾),它也可以是一个 RSS 页面, 或其他任何类型的页面。

    注:本文中的CI运行基于WAMPServer 环境。

    创建模型                                                           

    打开phpMyAdmin创建表。

     

    这里主要基于该表设计,表名为“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:这只是为了练习而已,所以,各个功能很乱,并无打算写一个完整的系统。

  • 相关阅读:
    PostgreSQL表空间、数据库、模式、表、用户/角色之间的关系(转)
    PostgreSQL学习手册-模式Schema(转)
    Python中的编码与解码(转)
    HttpRequest中常见的四种Content-Type(转)
    Django中对静态文件的支持(转)
    IPython的基本功能(转)
    GET请求Referer限制绕过总结
    Linux pwn入门教程(6)——格式化字符串漏洞
    CVE-2015-1641 Office类型混淆漏洞及shellcode分析
    我用着差不多的套路收拾差不多的骗子过着差不多的又一天!
  • 原文地址:https://www.cnblogs.com/fnng/p/5087437.html
Copyright © 2011-2022 走看看