实验楼的laravel 4.2 blog 教程(六)

#1、错误页面处理

如果用户访问的URL不存在或者服务器存在错误时,我们不希望返货一个错误的页面,而想返回一个友好提示的页面,在Laravel中可以很轻松地实现,Laravel有很简单的错误和日志处理,当服务器端存在错误时,app/start/global.php里默认有一个处理所有异常的异常处理程序:

App::error(function(Exception $exception)
{
    Log::error($exception);
});
它会把异常信息写到日志中,日志文件默认是app/storage/logs/laravel.log。

# 如果要显示一个友好的错误提示页面,我们可以创建一个视图:

php artisan generate:view error

#修改error.blade.php

@extends('_layouts.default')

@section('main')
<div class="am-g am-g-fixed">
  <div class="am-u-sm-12">
	<h1>Sorry, there is an error!<br/>
		return <a href="/">Index</a>
	</h1>
  </div>
</div>
@stop

#修改App/start/global.php 在App::error(function(Exception $exception)中增加:

return Response::view('error', array(), 500);
现在当访问出现错误时,就会出现错误提示页面


#2、404处理

#当访问的URL不存在时,我们也可以返回一个友好的提示页面,先创建一个视图

php artisan generate:view notFound

#修改notFound.blade.php

@extends('_layouts.default')

@section('main')
<div class="am-g am-g-fixed">
  <div class="am-u-sm-12">
	<h1>Sorry, the page you requested does not exist!<br/>
		return <a href="/">Index</a>
	</h1>
  </div>
</div>
@stop

#修改App/start/global.php 中增加:

App::missing(function($exception)
{
    return Response::view('notFound', array(), 404);
});

#3、配置文件

#在app/config 新建custom.php、添加

return array(
    'page_size' => 2,
);
现在你就可以在程序中使用了,把paginate(10)改成paginate(Config::get('custom.page_size')就行,其中custom对应app/config下的文件名,page_size对应相应配置文件中的键名,配置文件也可以根据你是开发环境还是生产环境进行不同的配置,详细的可以查看官方文档

如修改routes.php 的get('/') 的paginate里面的2改成 Config::get('custom.page_size')


#4、单元测试

#在app/tests 下创建MyTest.php ,定义一个类MyTest 继承TestCase 写测试代码

class MyTest extends TestCase {

    public function testIndex()
    {
        $this->call('GET', '/');
        $this->assertResponseOk();
        $this->assertViewHas('articles');
        $this->assertViewHas('tags');
    }

    public function testNotFound()
    {
        $this->call('GET', 'test');
        $this->assertResponseStatus(404);
    }
}

#添加phpunit 组件、在composer.json 的require-dev 添加

"phpunit/phpunit": "3.7.*"

#执行更新

composer update

#测试

vendor/bin/phpunit
稍等一会就会出现测试结果,在我们测试的时候如果想要做一些初始化操作,例如数据库迁移和填充等,可以定义在setUp方法中,切记要先执行parent::setUp,测试完成之后如果想要恢复现场,可以在tearDown方法中进行,如果在测试的时候想要使用特定的配置文件,我们可以在app/config/testing目录下创建,测试时它会自动覆盖原来的配置。

#部署到apache

wamp 参照:http://blog.youkuaiyun.com/small_rice_/article/details/21029595

lnmp 参照:http://blog.youkuaiyun.com/small_rice_/article/details/44986527

本节教程讲了错误处理优化、配置文件的使用、单元测试以及怎么部署到Apache服务器,你可以买一个域名和一个服务器,最好买VPS云服务器,虚拟空间非常有局限性,然后把你自己写的网站部署到服务器让大家一起访问。


代码:git clone http://git.shiyanlou.com/shiyanlou/laravel-blog-6

参照:https://www.shiyanlou.com/courses/document/425



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值