search
HomeBackend DevelopmentPHP TutorialTalk about the application of Shell in code refactoring_PHP tutorial

Talk about the application of Shell in code refactoring_PHP tutorial

Jul 13, 2016 pm 05:43 PM
codeshellcodeexistcharacterapplicationyesofTalk about itRefactor

代码重构(Code refactoring)有时是很枯燥的,字符串替换之类的操作不仅乏味,而且还容易出错,好在有一些工具可用,以PHP为例,如:Rephactor,Scisr等等,不过现成的工具往往意味着不够灵活,所以今天我要说说Shell在代码重构中的应用。

先来个简单的,假设我们要把PHP文件中的foo_bar全都替换成fooBar,那么可以如下:

方法一,使用Sed:

shell> find /path -name "*.php" | xargs sed s/foo_bar/fooBar/g
 


方法二,使用AWK:

shell> find /path -name "*.php" | xargs awk { gsub(/foo_bar/, "fooBar"); print; }
 


注:为了简单,我把结果直接打印到终端屏幕了,至于如何保存,稍后会说明。

接着说个复杂的:假设某个PHP项目,以前使用类之前必须调用一个名为“includeClass”的方法,现在改用类自动加载的方式,所以要删除硬编码的includeClass调用,出于美观的考虑,如果includeClass下面一行是空行的话,也一起删除,同时考虑大小写不敏感的因素。

重构前的代码示例:

01 02 includeClass(...);
03 echo a;
04
05 echo b;
06 includeClass(...);
07 includeClass(...);
08
09
10 echo c;
11
12 echo d;
13 includeClass(...);
14
15
16 echo e;
17 ?>
 


重构后的代码示例:

01 02 echo a;
03
04 echo b;
05
06 echo c;
07
08 echo d;
09
10 echo e;
11 ?>
 


在动手前,我们需要先摸摸底,了解一下大概的情况:

shell> grep -I -ri includeClass /path | more
 


其中,grep命令的参数乍一看不好记,不过只要按照我说的方法记,就永远不会忘:前面的参数看做英文,后面的参数看做拼音。至于参数的具体含义,请参阅man文档。

方法一,使用Sed编写脚本script.sh:

#!/bin/sh

for PHP in $@; do
    /bin/sed -i
        /includeClass/I {
            h
            d
        }

        /^$/ {
            x
            /includeClass/Id
            x
        }

        h
    $PHP
done
 


注:篇幅所限,我把正则写的比较简单

Sed的缺点是代码可读性比较差,优点是代码较短。另外内置的“-i”选项可以直接完成保存,这是我喜欢Sed的原因之一。

方法二,使用AWK编写脚本script.sh:

#!/bin/sh

for PHP in $@; do
    TMP=$(mktemp)

    /bin/awk
        BEGIN {
            IGNORECASE = 1
        }

        /includeClass/ {
            previous = $0
            next
        }

        /^$/ {
            if (previous ~ /includeClass/) {
                previous = $0
                next
            }
        }

        {
            previous = $0
            print
        }
    $PHP > $TMP

    /bin/cp -f $TMP $PHP
    /bin/rm -f $TMP
done
 


注:篇幅所限,我把正则写的比较简单

AWK的缺点是代码比较长,优点是代码可读性较好。另外程序中是通过生成一个唯一的临时文件来完成保存的。

Reminder: Sometimes it is not appropriate to directly overwrite the original file. After all, there may be some things that have not been carefully considered. If you use SVN, you will not have such concerns, because even if the original file is overwritten, it can still be passed before submission. svn diff" command to check for errors. Even if it is submitted, it can be restored to the previous version.

What if the script.sh script is called? Here is the most general example:

shell> find /path -name "*.php" | xargs /path/to/script.sh


Sed is suitable for writing simple tasks, and AWK is best for complex tasks. Practical combat is the best way to learn. For details, you can refer to materials such as Sed One Line and AWK One Line.

Note: The Sed and AWK used in this article refer to the GNU version.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478849.htmlTechArticleCode refactoring is sometimes very boring. Operations such as string replacement are not only tedious; It is also easy to make mistakes. Fortunately, there are some tools available, taking PHP as an example, such as: Re...
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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool