天变冷了,人也变得懒了不少,由于工作的需要,最近一直在学习CodeIgniter(CI)框架的使用,没有系统的从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>

定义页尾:

.../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>

不过,这里使用的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 -->

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 -->

这里使用了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:这只是为了练习而已,所以,各个功能很乱,并无打算写一个完整的系统。

再次用CodeIgniter实现简易blog的更多相关文章

  1. django开发个人简易Blog——数据模型

    提到数据模型,一定要说一下MVC,MVC框架是现代web开发中最流行的开发框架,它将数据与业务逻辑分开,减小了应用之间的高度耦合.个人非常喜欢MVC开发框架,除了具有上述特性,它使得web开发变得非常 ...

  2. 用django搭建一个简易blog系统(翻译)(三)

    06. Connecting the Django admin to the blog app Django 本身就带有一个应用叫作Admin,而且它是一个很好的工具 在这一部分,我们将要激活admi ...

  3. Django初体验——搭建简易blog

    前几天在网上看到了篇采用Django搭建简易博客的视频,好奇心驱使也就点进去学了下,毕竟自己对于Django是无比敬畏的,并不是很了解,来次初体验. 本文的操作环境:ubuntu.python2.7. ...

  4. django开发个人简易Blog—nginx+uwsgin+django1.6+mysql 部署到CentOS6.5

    前面说完了此项目的创建及数据模型设计的过程.如果未看过,可以到这里查看,并且项目源码已经放大到github上,可以去这里下载. 代码也已经部署到sina sea上,地址为http://fengzhen ...

  5. PHP实现简易blog

    最近,有时间看了点PHP的代码.参考PHP100教程做了简单的blog,网易云课堂2012年的教程,需要的可以找一下,这里面简单的记录一下. 首先是集成环境,这里选用的WAMP:http://www. ...

  6. 使用Django创建简易Blog

    网上看了个例子,但是自己却运行不同,最后终于知道了原因,记录下来.原来没有给settings.py里的INSTALLED_APPS添加blog.就像这样: 这是一个手把手的实例教程,本来学习笔记一样, ...

  7. 用django搭建一个简易blog系统(翻译)(四)

    12. Create the templates 你需要做三件事来去掉TemplateDoesNotExist错误 第一件,创建下面目录 * netmag/netmag/templates * net ...

  8. 用django搭建一个简易blog系统(翻译)(二)

    03. Starting the blog app 在这部分,将要为你的project创建一个blog 应用,通过编辑setting.py文件,并把它添加到INSTALLED_APPS. 在你的命令行 ...

  9. 用django搭建一个简易blog系统(翻译)(一)

    Django 入门 原始网址: http://www.creativebloq.com/netmag/get-started-django-7132932 代码:https://github.com/ ...

随机推荐

  1. Sublime Text 3专题

    MarkDown语法记笔记 1.下载&&安装 下载 常用插件安装 Submlit使用教程 [如何优雅地使用Sublime Text3] 2.Sublime Text 便捷技巧 [以PH ...

  2. 【C-01关键字】

    一.语句引导关键字 for   while   swith  if  do   goto   return 二.限定关键字 const  static   extern 三.预编译关键字 #inclu ...

  3. Linux下安装tomcat

    安装tomcat之前首先安装jdk,这个看前面的帖子. 下面说centeros6.5安装tomcat7的方法: 1.将apache-tomcat-7.0.29.tar.gz文件上传到/home/zha ...

  4. Apache Lucene 4.5 发布,Java 搜索引擎

    Apache Lucene 4.5 发布了,该版本提供基于磁盘的文档值以及改进了过滤器的缓存.Lucene 4.5 的文档请看这里. Lucene 是apache软件基金会一个开放源代码的全文检索引擎 ...

  5. libnode 0.4.0 发布,C++ 语言版的 Node.js

    libnode 0.4.0 支持 Windows ,提升了性能,libuv 更新到 0.10.17 版本,libj 更新到 0.8.2 版本. libnode 是 C++ 语言版的 Node.js,和 ...

  6. android handler 简介

    android的handler 是一个神奇东西,处理异步消息的时候,我们离不开他.那么他的具体的介绍是什么了? Handler基本概念:      Handler主要用于异步消息的处理:当发出一个消息 ...

  7. objective-c(框架)

    框架指objective-c的foundation库,下面的例子中给出几个常见用的类及其方法. 数值对象 NSNumber *intNum; NSNumber *longNum; NSNumber * ...

  8. Java设计模式7:适配器模式

    适配器模式 适配器模式说的是,可以把一个类的接口变换成客户端所期待的另一种接口,使得原本因接口不匹配而无法在一起工作的两个类可以一起工作. 适配器模式的用途 适配器模式的用途,在网上找了一幅图,挺形象 ...

  9. Unity3D ogg下载并播放

    那天说了c#不好弄ogg和mp3的解码,然后就发现打脸了. 找到了一些开源的解码器,由于ogg的音质容量比要明显好于mp3,主要弄ogg的播放. 由于自带解码器,可以实现全平台下载并播放,甚至可以实现 ...

  10. 用python语言讲解数据结构与算法

    写在前面的话:关于数据结构与算法讲解的书籍很多,但是用python语言去实现的不是很多,最近有幸看到一本这样的书籍,由Brad Miller and David Ranum编写的<Problem ...