search
HomeBackend DevelopmentPHP TutorialLaravel Large Project Tutorial Series (6) Optimization, Unit Testing and Deployment

This tutorial will explain error handling, use of configuration files, unit testing and deployment to Apache server.

1. Error handling

If the URL visited by the user does not exist or there is an error in the server, we do not want to return an error page, but want to return a friendly prompt page, which can be easily implemented in Laravel, Laravel There is very simple error and log processing. When there is an error on the server side, there is an exception handler in app/start/global.php by default to handle all exceptions:

<code><span>App</span><span>::error(function(Exception</span> $<span>exception</span>)
<span>{
    <span><span>Log</span>:<span>:<span>error($exception)</span></span></span>;
<span>}</span></span>);</code>

It will write the exception information to the log, The default log file is app/storage/logs/laravel.log.

If we want to display a friendly error prompt page, we can create a view:

<code><span>$ </span>php artisan <span>generate:</span>view error</code>

Modify error.blade.php:

<code><span>@extends</span>(<span>'_layouts.default'</span>)

<span>@section</span>(<span>'main'</span>)
    Sorry, there <span>is</span> an error!
        <span>return</span> Index

<span>@stop</span></code>

Add in App::error(function(Exception $exception):

<code><span>return</span> Response<span>::view</span>(<span>'error'</span>, <span>array</span>(), <span>500</span>);</code>

Now when an access error occurs, an error prompt page will appear:

2.404 processing

When the accessed URL does not exist, we can also return a friendly prompt page, first create a view:

<code>$ php artisan generate:view <span>not</span><span>Found</span></code>

Modify notFound.blade.php:

<code><span>@extends</span>(<span>'_layouts.default'</span>)

<span>@section</span>(<span>'main'</span>)

    <span>Sorry</span>, the page you requested does <span>not</span> exist!
        <span>return</span><span>Index</span><span>@stop</span></code>

Add in app/start/global.php:

<code>App::missing(<span><span>function</span><span>(<span>$exception</span>)</span>
{</span><span>return</span> Response::view(<span>'notFound'</span>, <span>array</span>(), <span>404</span>);
});</code>

Now when the URL you visit does not exist, the following page will appear:

3. Configuration file

Sometimes we may need some values ​​that have been set in advance. When the program is executed, we only need to reference this value, such as the number displayed on each page when displaying in paging. We can use the configuration file, in Laravel It is also very convenient to use configuration files in app/config. We can create a new one named custom.php and add:

<code><span>return</span><span>array</span>(
    <span>'page_size'</span> => <span>10</span>,
);</code>

Now you can use it in the program, put paginate(10) Just change it to paginate(Config::get('custom.page_size'), where custom corresponds to the file name under app/config, page_size corresponds to the key name in the corresponding configuration file, and the configuration file also You can configure different configurations according to whether you are a development environment or a production environment. For details, you can view the official documentation.

4. Unit testing

Before the website goes online, we usually need to perform unit testing. Laravel provides a very convenient unit testing module. . I only implement an example here. We can first create a file named MyTest.php under app/tests and define a class named MyTest in it. Remember to inherit the TestCase class. Then you can write the test code:

<code><span><span>class</span><span>MyTest</span><span>extends</span><span>TestCase</span> {</span><span>public</span><span><span>function</span><span>testIndex</span><span>()</span>
    {</span><span>$this</span>->call(<span>'GET'</span>, <span>'/'</span>);
        <span>$this</span>->assertResponseOk();
        <span>$this</span>->assertViewHas(<span>'articles'</span>);
        <span>$this</span>->assertViewHas(<span>'tags'</span>);
    }

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

After the test code is written, we need to install a phpunit component, add it to require-dev in composer.json:

<code><span>"phpunit/phpunit"</span>: <span>"3.7.*"</span></code>

and then composer updateinstall it , execute vendor/bin/phpunit after completion, and the test results will appear after a while. If we want to do some initialization operations during our test, such as database migration and filling, etc., we can define it in the setUp method. , remember to execute parent::setUp first. If you want to restore the scene after the test is completed, you can do it in the tearDown method. If you want to use a specific configuration file during testing, we can do it in app/config Created in the /testing directory, it will automatically overwrite the original configuration during testing.

5. Deploy to Apache

After passing the test, we can deploy the website to the application server. In the production environment, we should set debug in app/config/app.php to false . Here we explain how to deploy to the Apache server. First of all, let me declare that the LAMP environment here is installed through tasksel. We first install the mod_rewrite module:

<code>$ <span>sudo</span> a2enmod rewrite</code>

and then set the permissions of the /var/www directory to 777. This directory is the directory where the website is stored. :

<code>$ sudo chmod -R <span>777</span> /<span>var</span><span>/www/</span></code>

Then copy the project folder we developed into this folder. Here is the blogfolder:

<code><span>$ </span>cd /var/www/
<span>$ </span>cp -r ~<span>/laravel-project/blog</span><span>/ .</span></code>

The above development project path must be the same as your own, and then we need to put app/ Change the permissions of the storage directory to 777, because the storage folder will store logs, etc., involving write operations:

<code><span>$ </span>cd blog/app/
<span>$ </span>chmod -<span>R</span><span>777</span> storage/</code>

Configure the server below:

<code>$ sudo vim /etc/apache2/sites-enabled/<span>000</span>-<span><span>default</span>.conf </span></code>

Change DocumentRoot/var/www/html to DocumentRoot /var/www/blog/public, then modify apache2.conf:

<code>$ <span>sudo</span> vim /etc/apache2/apache2.conf</code>

Add

<code>AllowOverride <span>all</span></code>

to

<code>Options Indexes FollowSymLinks
AllowOverride <span>None</span><span>Require</span><span>all</span> granted</code>

, now start the Apache server:

<code>$ <span>sudo</span> service apache2 start</code>

Visit localhost or in the browser 127.0.0.1You can see our website, and the deployment is complete.

6. Summary

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

最后的代码下载:

<code><span>$ </span>git clone <span>https:</span>/<span>/github.com/shiyanlou</span><span>/laravel-blog-6.git</span></code>

本文详细出自http://www.shiyanlou.com/courses/123,转载请注明出处

以上就介绍了laravel大型项目系列教程(六)之优化、单元测试以及部署,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Dependency Injection in PHP: Avoiding Common PitfallsDependency Injection in PHP: Avoiding Common PitfallsMay 16, 2025 am 12:17 AM

DependencyInjection(DI)inPHPenhancescodeflexibilityandtestabilitybydecouplingdependencycreationfromusage.ToimplementDIeffectively:1)UseDIcontainersjudiciouslytoavoidover-engineering.2)Avoidconstructoroverloadbylimitingdependenciestothreeorfour.3)Adhe

How to Speed Up Your PHP Website: Performance TuningHow to Speed Up Your PHP Website: Performance TuningMay 16, 2025 am 12:12 AM

ToimproveyourPHPwebsite'sperformance,usethesestrategies:1)ImplementopcodecachingwithOPcachetospeedupscriptinterpretation.2)Optimizedatabasequeriesbyselectingonlynecessaryfields.3)UsecachingsystemslikeRedisorMemcachedtoreducedatabaseload.4)Applyasynch

Sending Mass Emails with PHP: Is it Possible?Sending Mass Emails with PHP: Is it Possible?May 16, 2025 am 12:10 AM

Yes,itispossibletosendmassemailswithPHP.1)UselibrarieslikePHPMailerorSwiftMailerforefficientemailsending.2)Implementdelaysbetweenemailstoavoidspamflags.3)Personalizeemailsusingdynamiccontenttoimproveengagement.4)UsequeuesystemslikeRabbitMQorRedisforb

What is the purpose of Dependency Injection in PHP?What is the purpose of Dependency Injection in PHP?May 16, 2025 am 12:10 AM

DependencyInjection(DI)inPHPisadesignpatternthatachievesInversionofControl(IoC)byallowingdependenciestobeinjectedintoclasses,enhancingmodularity,testability,andflexibility.DIdecouplesclassesfromspecificimplementations,makingcodemoremanageableandadapt

How to send an email using PHP?How to send an email using PHP?May 16, 2025 am 12:03 AM

The best ways to send emails using PHP include: 1. Use PHP's mail() function to basic sending; 2. Use PHPMailer library to send more complex HTML mail; 3. Use transactional mail services such as SendGrid to improve reliability and analysis capabilities. With these methods, you can ensure that emails not only reach the inbox, but also attract recipients.

How to calculate the total number of elements in a PHP multidimensional array?How to calculate the total number of elements in a PHP multidimensional array?May 15, 2025 pm 09:00 PM

Calculating the total number of elements in a PHP multidimensional array can be done using recursive or iterative methods. 1. The recursive method counts by traversing the array and recursively processing nested arrays. 2. The iterative method uses the stack to simulate recursion to avoid depth problems. 3. The array_walk_recursive function can also be implemented, but it requires manual counting.

What are the characteristics of do-while loops in PHP?What are the characteristics of do-while loops in PHP?May 15, 2025 pm 08:57 PM

In PHP, the characteristic of a do-while loop is to ensure that the loop body is executed at least once, and then decide whether to continue the loop based on the conditions. 1) It executes the loop body before conditional checking, suitable for scenarios where operations need to be performed at least once, such as user input verification and menu systems. 2) However, the syntax of the do-while loop can cause confusion among newbies and may add unnecessary performance overhead.

How to hash strings in PHP?How to hash strings in PHP?May 15, 2025 pm 08:54 PM

Efficient hashing strings in PHP can use the following methods: 1. Use the md5 function for fast hashing, but is not suitable for password storage. 2. Use the sha256 function to improve security. 3. Use the password_hash function to process passwords to provide the highest security and convenience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool