php $content,【转载】 PHP编程技巧:$content->add_post()

全宇宙最好的编程语言 PHP 入门是非常简单的,但编程是件非常复杂的事情,代码的性能、兼容性、维护成本等等都是需要考虑的,这篇内容就说说 PHP 的编程技巧,笔者水平有限,只能将自己知道的东西分享出来,高手请略过。

下面以【爱玩电脑】后台添加内容的代码片段做示例,主要是将程序的“逻辑判断”和“操作过程”还有“视图”分开,即大家常说的 MVC 模式。

先看“逻辑判断”的部分代码 content.php , 主要使用 php switch() 进行逻辑判断实现操作控制 。

$action = get('action');

switch ($action)

{

//添加内容

case 'add':

$data['catalog_option'] = $content->catalog_option();

template2('content_add', $data);

break;

//添加内容处理

case 'add_post':

$array = $content->add_post();

echo json_encode($array);

exit();

break;

}

$content->add_post()

浏览器访问负责“逻辑判断”的文件 content.php ,程序中通过 $action 变量判断操作,然后调用负责“操作过程”的文件 class/content.php 中相应的方法。

content::add_post()

/**

* add_post()

* return array('error', 'message')

*/

public function add_post ()

{

$title = post('title');

$catalog = post('catalog');

$keywords = str_replace(',', ',', post('keywords'));

$description = htmlspecialchars(post('description'));

$tags = str_replace(',', ',', post('tags'));

$text = post('text');

$time = post('time');

$time = strtotime($time) ? strtotime($time) : time();

$comment = post('comment');

$comment = $comment ? 1 : 0;

$remote = post('remote');

$yuan = post('yuan');

$yuan = $yuan ? 1 : 0;

$thumb = post('thumbInput');

//表单验证

if (!$title || !$text)

return array("error"=>1, 'message'=>'标题和正文必须填写');

$id = $this->mysql->insert('INSERT INTO `xxx_content` (`user_id`, `catalog_id`, `update_time`, `allow_comment`, `visit`, `title`, `tags`, `keywords`, `description`, `thumb`, `yuan`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);', array(user::id(), $catalog, $time, $comment, rand(10, 99), $title, $tags, $keywords, $description, $thumb, $yuan));

if ($id <= 0)

{

return array("error"=>1, 'message'=>'添加失败 Table_1');

}

else

{

$text = $this->text_tag_link($text);

$this->update_tag($tags, $id);

if ($remote)

$text = $this->remote($text);

$ok = $this->mysql->insert('INSERT INTO `xxx_content_text` (`content_id`, `text`) VALUES (?, ?);', array($id, $text));

if ($ok <= 0)

return array("error"=>1, 'message'=>'添加失败 Table_2');

else

return array("error"=>0, 'message'=>$id);

}

}

因为整个操作过程都在 conntent::add_post() 中完成所以代码比较长,主要实现了表单验证、正文处理、设置标签、下载远程图片等功能。

因为成功增加内容后需要一个“查看内容”的按钮,所以 content::add_post() 中将所有提示信息以数组形式返回 array('error'=>true, 'message'=>'abc....') ,方便 content.php 更容易与前台对接。

至于“视图”Aowana 做得非常简单,并没有使用模板引擎,只是写了个 template2() 方法把视图和程序分离而已,下面是调用视图的示例:

//添加内容

case 'add':

$data['catalog_option'] = $content->catalog_option();

template2('content_add', $data);

break;

~完~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值