Evergreen transfer PHP development

大话转岗PHP开发小结

Preface

Recently, due to the internal transfer of the company, it is always a strong type of writing, and the weak type language has also been exposed. Some, such as: nodejs, python, doing some auxiliary services, data collection, just this opportunity can be used to use, plus the understanding and experience of the backend before, it is easy to get started, here the development process encountered Some problems solutions and their own understanding of PHP, and partial architecture in the project

The version of PHP7 has been entered, which has made a lot of adjustments, especially in performance.

大话转岗PHP开发小结 PHP frame has a lot of powerful functions, super global variables, magic functions, magic variables, can be pHP The project is expanded, data type operation, HTTP information acquisition, etc., by installing expansion, the file built-in function calls most or the direction-oriented process, by calling the function, incoming type data and dependent data, here Start some uncomfortable, custom-oriented development habitual type variable / object point outfunction.

Now PHP development can choose to use the oriented process or object-oriented. The earliest PHP version does not support object-oriented features, and PHP5 has good support for OOP. Many PHP developers have no systematic learning OOP related knowledge. Many PHP developers or old projects, including long projects, are also biased towards process development, so they will be exposed to a multi-directional process-oriented project

encounter some partial application business development during project development. It seems useful to be class, but there is no use of object-oriented features to abstract the business. For example, each business feature in the project corresponds to a class. Most of the class is logical function, and then expand AutoLoad, automatic Include PHP file, such as passing the L function into the class name to be called, constructing the PHP file path, using the include, then return to the class instance object, just through class files to distinguishCan function, did not use object-oriented characteristics, or biased to process ideas in development

PHP5 starts to provide good support for OOP, basically, and Java, C # face-oriented syntax, you can use naming Space, Package Interface, Abstract, Polymorphism: Implements, Extends, PHP7 also supports multi-inheritance Trait, easy to encapsulates some public functions, through the PSR4 specification, introducing the Composer implementation AutoLOAD, can be well-developed

PHP development is still more flexible, can also be object-oriented or object-oriented, according to specific business scenario

Using Composer PSR4

Add Composer in the project .json file, configure
  •  {"AutoLoad": {"library /}}}  {" library \\}}}    
    In the directory where the composer.json file is located, automatically download the Download Vendor / Composer AutoLoad related file
  • Composer Install
        Index include autoload.php  
    include_once “vendor / autoload.php”;
  •  Note that when configuring modifications, the content is changed,     Composer dump-autoload -o 
  •      Coding Problem: 
    When you just learn PHP grammar, it is a weak type, no need to define Variable type, parameter type, return value type, there will be some inconsistency in children’s shoes, there is no habitle, uncertain types are weird, and there is always no mistake, and weak type does not have the IDE in the process of encoding. Some types of types of incorrect types, only reports wrong when running, you can know the error here, the error prompts lag. Especially from the DB query data is a stdclass / array. The obtained data does not correspond to one entity class. It cannot know which fields are available. You need to pass the SQL statement of the query, and then you can know the data field information, essentially. This is very difficult, affecting the development efficiency
  • PHP now supports TypeHint, with a definition type to be determined type variables, parameters, return types, especially the table data model class, this After obtaining the data object, all data fields can be perceived, which is easy to expand the development and maintenance

According to the scene, it cannot be said that all types of definitions are written to a strong type because they are used to using strong shape.

/ ** * Class MJOP * @Property INT $ ID Work ID * @Property String $ Name Work Name * @Property Int $ SALY Salary * / Class MJOP {} / ** * Class MWORKER * @Property string $ name employee name * @Property int $ with age * @Property MJOP $ JOP Work * / class mworker {} class worker {/ ** * Get employee information *@Param Int $ ID * @Return MWORKER | stdclass * / public function get (int $ ID): stdclass {// mysql select return new stdclass ();}} class logic {/ ** * Get employee description * @Param Int $ Workid * @return string * / public function desc: string {$ worker = new worker (); $ mworker = $ worker-> get ($ Workid); return ‘name:’. $ mworker-> Name. ‘, age:’. $ mworker-> agn. ‘, work:’ + $ mworker-> jop-> name. ‘, salary:’. $ mworker-> jop-> salary;}}

By defining variable types to get code perception

 / ** @var logic $ logic * / $ logic = new logic ()     The weak type is more than two large: 
Because PHP is a weak type, when it is more than the type, it will often be due to one Be careful to drop the pit, the table function and type comparison table

ask you, see these forms are afraid, there is 10,000 grass mud horses in the heart, and instantly become a blame Small eyes
 [1    
expression

GetType ()

iSSET ()

Boolean: IF ($ x) 大话转岗PHP开发小结

Trier true True FALSE $ x = null; True True False FALSE VAR $ x; True True False False NULL True TRUE False False Array True False TRUE False True True False TRUE $ x = 1; False true TRUE False True True $ x = 0 true True False $ x = -1; False False True TRUE $ x = “1”; False true True $ x = “0”; TRUE True False String 】 False True True loose Comparison == True False 1 0 “1” True true False true TRUE true false true false True true True
$ x = false; Boolean
$ x = true; Boolean False True
$ x = 42;
$ x = “-1”;
False True $ x = “php”; String
$ x = “True”; String False True True
$ x = “false”;
“0” “- 1” NULL Array () “” “
True faLse true true true true
FALSE

True FALSE 0 False True FALSE true true [ False true False False False “1” true true False False True false false false False False True NULL False True true False False False TRUE False False False False False TRUE “PHP” True FALSE “” False True False TRUE False False true False False 】 True True False – 1 “1” “0” ” 1 “ [ False False False False False true False False False FALSE False FALSE [ False False False False False “0” [ False
True true true False False False False False
true False True TRUE – 1 True False False False True
true true true False False False False False False True False False
False TRUE False False False
true True Array () False TRUE False
False False False False true False
Strict comparison =====
” PHP “ ” “ True False False False False
False False False
True FALSE False false false false false False 0 False False False True
False False False False False – 1 False False False TRUE
False False False False True False False False False
False

False False “- 1” False False NULL FALSE False False Array () FALSE False FALSE False False False False True False False False False False FALSE “” False False False False False False False False TRUE Reference official type comparison document IDE can’t make an error prompt for the defined variable, because no defined type IDE does not know the type of variable, there is no way to make a mistake reminder, often need to output it to the page when running PHP weak type, vulnerability example PHP dynamic characteristics, which can be dynamically instantiated, dynamically added attributes, dynamic call functions, etc., through these features can be packaged in a simple code package Name. ‘, Hair:’. $ This-> Hair; if (!! $ This -> AGE)) $ desc = $ desc. ‘, age:’. $ this-> age; echo $ desc. “\ r \ n”;} / ** * Data logic processing * @Param $ condition * @Return Bool | String * / Public Function Handle ($ condition) {if (is_int ($ condition) {// … … logic return ‘digital processing result’;} else if (is_string ($ condition) {/ / … Logic Return ‘string processing result’;} else if (is_ARRAY ($ condition) {// ……………………………………………………………………………… XM-> Name = ‘Code San’; $ XM-> Hair = 80; // Method 1 – Variable as the attribute name // $ field = ‘agn’; // $ weLELOPER -> $ fieldage = 20; // 2 – Directly set the attribute value $ xm-> agn = 20; // —– Dynamic call object function —– // Variable as a function name call $ fn = ‘introduce’; if (Method_exists ($ XM) , $ fn)) $ xm -> $ fn (); // —– Dynamic Instantiation —– / / Method 1 – Variables As the class name to instantiate $ classname = ‘developer’; / * * @var developer $ xf * / $ xf = new $ classname (); $ xf-> name = ‘small party; $ xf-> hair = 30; $ xf-> introduce (); // —- – Property traversal —— foreach ($ xf as $ key => $ val) {Echo $ key. ‘=’. $ Val. “\ R \ n”;} // —— Parameter type and return value support multiple types —— $ r = $ xf-> handle (null); if ($ r === false) {echo ‘processing failed’;} else {echo $ r;} // —— Function variable ——$ fn = function () {echo ‘do something’;}; $ fn (); Change error reporting behavior: // mode 2: Function call setting error level error_reporting (e_all & ~ e_notice); Error control operator @ to suppress a specific error. Placing this operator before the expression, any of the errors will not appear. register_shutdown_function registration a callback, which will perform completion or exit in the script After being called. set_error_handler ourselves to handle errors in the run set_exception_handler set the default exception handler, used to use the exception captured by TRY / CATCH way 1: FastCGI mode is currently a reasonable way to pass the single case mode, guarantee in the current request The data connection under operation only creates an object way 2: PTHREAD expansion CLI Distributed Task Distribution Tutorial Workerman PHP realization a network library Tierature thread is scheduled by the operating system kernel, we cannot intervene, the science is a user-state program , Equivalent to the application yourself. Because it is a user-state program, it is equivalent to multiple sweepers that will run in a thread. To note that only the kernel’s scheduling of threads can take advantage of CPU’s multi-core resources, let the program make parallel, so in oneMultiple advantages in a thread are unable to do parallel. User-state and kernel state: Swoole 4.0 new price Application Server Architecture Service Deployment: PHP7 + NGINX + PHP-FPM Gitlab code hosting, automatic publishing environment ELK log Services Elasticsearch Search Engine LogStash / FileBeat User Log Processing Kibana is used to detect the structured data stored in ElasticSearch According to the business distributed cluster REDIS CODIS distributed deployment MongoDB Log record, BI processing All Alibaba Cloud servers, code hosting self-built GitLab services, merged from development branches to GitLab Environmental branches Automatic deployment to the corresponding environment server Test environment Test -app.sflyq.com Test database Company Internet access GitlaB Release Preoperant Environment YF-APP.SFLYQ.COM Production Database Company Inline Access Production Environment app.sflyq.com Gitlab Master Local test environment Docker deployed A familiar language to another relatively unfamiliar language, language is just a tool, using suitable tools in a suitable scene, from your familiar business to unfamiliar business, leaving your comfort, hug changes to grow Switching language learning costs in the same backend are still relatively low, mainly for the idea of ​​backend development, experience is to be shared, just changing a language to implement When the company has developed to a certain The scale, the position of the job function is very fine, doing application-developed children’s shoes fail to contact the server architecture, there is no chance to contact the technology, in addition to completing business demand development, or business demand development, this year is developing for personal growth The limitations are high, need to be expanded in the work, understand and learn from the technology within the company, patiently waiting for the opportunity At the end, the focus is the working attitude of development should have. I feel that most of the development of participation in the project is universally responsible and is not strong. There is no need to think, but it is a shuttle code. According to the product’s logic process code, the function test is on the line, then there is no problem, then After the merges, the two ear will not smell the world, as a development in participating projects, what kind of position you are in the project, what kind of working attitude you are From the perspective of the project, all participation should be involved The project is a selfChildren need to take the initiative to pay attention to the data and follow-up development of the project, accompanied by children grow, slowly have a sense of accomplishment From the technical perspective, the project needs function is developed as a house, which needs to analyze Business needs provide reasonable design, appropriate abstract and use design models, only to make the foundation to ensure subsequent maintenance and expansion when developing, avoiding technical debt The first article in 2019, I wish you all the best in the new year! Welcome to the “Wai Wai Web Development]
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment

True False False False False [ False False False False False false
False False False False False FALSE
False “PHP” False False FALSE
Just contact PHP to see these When a table is dizzy, you need to pay special attention to the following types when developing. To use ‘===’, some function types have been able to determine that the multi-type parameters are not allowed to limit the type. It is also good to see this form on the back proficiency. It is also very good. The comparison between the common type has been deeply entered into the mind Other questions: PHP flexibility said that there is a problem under such a weaker type, and the advantages of weak type, weak type An obvious advantage is flexible
Unique characteristics memory is not resident PHP Web server development, server deployment Multi-dependent FastCGI process manager, Static variable and C # include Java life cycle, C # / Java web application service process static variable is in memory and sharing Most of the PHP uses NGINX deploying FASTCGI process management. The process of receiving the request is independent of each other. Request to respond to recycle resources, there is no resident. Of course, PHP is also a resident, CLI (command line mode), is the Web application service of the Swoole framework development deployment, the Swoole framework development deployment is also a memory resident Error level In the past, when the error was developed, the execution encountered error will directly throw an exception. The try catch can capture the error exception. The exception does not continue to execute the following content, PHP will be different, depending on the different error levels The implementation mechanism PHP has several erroneous severity levels. The three most common types of information are erroneous (error), notifications and warnings (WARNING). They have different severity: E_ERROR, E_NOTICE and E_WARNING. The error is a serious problem during the run, usually because the code error is made, must fix it, otherwise the PHP will stop execution. Notification is the recommended nature information because the program code may cause problems during the execution period, but the program will not stop. The warning is a non-fatal error, and the program execution will not be suspended. PHP can control whether the error is displayed on the screen (which is useful in development) or hides the log log (for formal environment) # Way 1: Configure php.inierror_reporting = e_ALL & ~ E_NOTICE
In-line error suppression: PHP’s Error and Exception Capture Problem: Error is detected The problem is highly likely to make the program unable to run, and Exception is a problem, but the program continues to run unaffected. The Error type cannot be captured in the previous version of the PHP7, only the Exception type can only be captured. The ERROR and Exception have inherited the throwable interface, so that ERROR is captured, and the version below PHROR can also capture Error Connection pool Generally, the connection pool is generally used in the database development, and the time consumption of the data operation efficiency is improved by using the connection pool to re-establish the connection. The effect is especially obvious under high concurrent business scene. Since most PHP application services are currently managed using Fastcgi, each request server assigns a processDealing, the process resource will be automatically recycled after returning the result, because this factor cannot establish a connection pool
can be expanded through the SWOOL to implement the data connection pool service, pass the SQL to the service to perform return data, Swoole memory, resident, application client connection break On-connection pool service process resources do not automatically recycle Multi-thread thread is the smallest of operating system capable of operational scheduling unit. It is included in the process and is the actual operation unit in the process. A thread refers to a single order of control flow in the process. You can concurrent multiple threads in a process. Each thread performs different tasks Swoole is a bottom network library Gearman
Simple sentence, when executed, if the code we write is executed, these code is running in the user state; when the system is called After calling, the code in the next kernel will execute, the code in the kernel is the operation in the internal nucleus
Code hosted and test environment:
Recent phase sensation