laitimes

Strive to be an excellent PHP developer

author:Jay's lab
This article was first published on GitBook.cn and can be published on third-party platforms due to the one-year exclusivity period. Due to the rush of time, coupled with the limited level of the author, there are shortcomings, and I hope that the majority of readers will bear with and guide.
Strive to be an excellent PHP developer

Linguistic features

PHP is indeed a distinctive language (second only to Python)

Object-oriented

Since PHP5, PHP has a complete object model, including classes, abstract classes, interfaces, inheritance, constructors, reflections, cloning, and exceptions, among others. Here are the new features in PHP 5.3-PHP 7.2 regarding object orientation:

  • Namespace (PHP5.3, better organization classes)
  • Traits (PHP5.4, solves the problem of multiple inheritance scenarios)
  • Anonymous Class (PHP7.0)
  • Importing a Set of Classes (PHP7.0)
  • Visibility of Class Constants (PHP7.1)
  • Multi-Exception Capture Handling (PHP7.1)
  • Allows overriding abstract methods (PHP7.2)

Function Expressions

UNLIKE JAVA, PHP TREATS FUNCTIONS AS "FIRST-CLASS CITIZENS", AND IF YOU PREFER FUNCTIONAL PROGRAMMING, PHP WON'T DISAPPOINT YOU. Here are the new features in PHP 5.3-PHP 7.2 regarding functions:

  • Closures (PHP5.3)
  • 闭包支持$this(PHP5.4)
  • Closure::call() (PHP7.0)

Asynchronous programming

As we all know, PHP is a single-threaded synchronous language. Prior to PHP 5.5, the only way to improve performance was to write code in a multi-process or multi-threading (pthreads) way. However, with the official introduction of PHP 5.5 Generator, asynchronous is possible. Here are the new features in PHP5.3-PHP7.2 for asynchronous programming:

  • Generator(PHP5.5)

Metaprogramming

PHP enables metaprogramming in a variety of ways through reflection APIs and magic methods. For example, it is possible to emulate the missing object-oriented feature of PHP - overloading - by magic methods. Here are the new features in PHP5.3-PHP7.2 regarding the magic method:

  • __callStatic (PHP5.3)
  • __invoke() (PHP5.3)

PHP Standard Library

The PHP standard library provides built-in data structures, iterators, interfaces, exceptions, functions, and file handling.

data structure

  • SplDoublyLinkedList 双链表
  • SplStack 栈
  • SplQueue 队列
  • SplHeap 堆
  • SplMaxHeap 最大堆
  • SplMinHeap minimum heap
  • SplPriorityQueue 优先队列
  • SplFixedArray 固定数组
  • SplObjectStorage object container

Iterators

  • AppendIterator 附加迭代器
  • ArrayIterator 数组迭代器
  • CachingIterator 缓存迭代器
  • CallbackFilterIterator — 回调过滤迭代器
  • DirectoryIterator — 目录迭代器
  • EmptyIterator — 空迭代器
  • FilesystemIterator — 文件系统迭代器
  • FilterIterator — 过滤迭代器
  • GlobIterator — Glob迭代器
  • InfiniteIterator — 无限迭代器
  • IteratorIterator — 迭代器迭代器
  • LimitIterator — 1,000,000,000
  • MultipleIterator — 多重迭代器
  • NoRewindIterator — 无倒回迭代器
  • ParentIterator — why not?
  • RecursiveArrayIterator — 𑀥
  • RecursiveCachingIterator — 递归缓存迭代器
  • RecursiveCallbackFilterIterator — 递归回调过滤迭代器
  • RecursiveDirectoryIterator — 递归目录迭代器
  • RecursiveFilterIterator — 递归过滤迭代器
  • RecursiveIterator — 𐕈ᬹᬹᬍᬹ
  • RecursiveRegexIterator — ʹ
  • RecursiveTreeIterator —the 𑁁 𑀢ᬶᨤ
  • RegexIterator — 正则迭代器

interface

  • Countable —可计算接口
  • OuterIterator —外部迭代器接口
  • RecursiveIterator(s)
  • SeekableIterator —可查找迭代器接口

abnormal

  • BadFunctionCallException —错误函数调用异常
  • BadMethodCallException —错误方法调用异常
  • DomainException —作用域异常
  • InvalidArgumentException —非法参数异常
  • LengthException —长度异常
  • LogicException —逻辑异常
  • OutOfBoundsException —违背安全原则异常
  • OutOfRangeException —越界索引异常
  • OverflowException —上溢异常
  • RangeException —范围异常
  • RuntimeException —运行时异常
  • UnderflowException —下溢异常
  • UnexpectedValueException —意外数值异常

function

  • class_implements — Returns all interfaces implemented by the specified class.
  • class_parents —Returns the parent class of the specified class
  • class_uses —Returns traits used by the specified class
  • iterator_apply —A user-defined function is called for each element in the iterator
  • iterator_count —Counts the number of elements in the iterator
  • iterator_to_array —Copies elements from the iterator to an array
  • spl_autoload_call — An attempt was made to call all registered __autoload() functions to mount the request class
  • spl_autoload_extensions — Registers and returns the default file extension used by spl_autoload function
  • spl_autoload_functions —Returns all registered __autoload() functions.
  • spl_autoload_register — Registers a given function as an implementation of __autoload
  • spl_autoload_unregister — Unregister the registered __autoload() function
  • spl_autoload — The default implementation of the __autoload() function
  • spl_classes - Returns all available SPL classes
  • spl_object_hash —返回指定对象的hash id

Document processing

  • SplFileInfo — The SplFileInfo class provides a high-level object-oriented interface to the information of a single file.
  • SplFileObject — SplFileObject provides an object-oriented interface for files.
  • SplTempFileObject — SplFileObject provides an object-oriented interface for temporary files.

Various classes and interfaces

  • ArrayObject — The ArrayObject class allows objects to be used as arrays
  • SplAbserver —The SplAbserver interface is used with the SplSubject to implement the observer design pattern.
  • SplSubject —SplSubject接口与SplObserver一起使用以实现观察者设计模式。

Why is the best language scolded?

MM: You can make everyone in this forum quarrel, and I'll go with you tonight. A software engineer: PHP is the best language! A certain forum is really fried, all kinds of quarrels...... A certain MM: I've served you, let's go, you can do whatever you want. A software engineer: Not today, I have to convince them that PHP must be the best language......

PHP is always the worst hacked in the chain of disdain for programming languages. But why do some people clamore PHP as the best language in the world, while others denounce PHP in all sorts of ways?

The learning threshold is low

By shielding more complex language features such as memory management, pointers, and C-like syntax, PHP beginners can quickly become familiar with the language. The nature of dynamic languages also makes type checking unperceptible to beginners. Coupled with an easy-to-build runtime environment, rich built-in APIs, and an active technical community, isn't this the "best language in the world" in the eyes of a beginner programmer?

Of course, this is also a fuse for being hacked, a programmer does not know pointers, asynchronous IO, threads, locks, enumerations, dictionaries, generics... Is this still a programmer?

Historical baggage

PHP is not like most well-known languages that were born in well-known organizations or companies. PHP originated in 1995, when the 17-year-old father of PHP (Rasmus Lerdorf) wrote a server script based on the Perl language to track and collect information about browsing his personal website. Since the main function of the first is to convert forms and collect information, this server-side script is named Personal Home Page Tools/Form Interperter, or PHP/FI for short. This is the original reason for the naming of PHP. Since PHP was originally intended to be just a tool, and Lerdorf was a very good programmer, language design was not his specialty, so PHP has a lot of historical baggage.

  • Confusing function naming, Linux C style coexists with camel naming
  • Misused string connectors (.)
  • Confused order of parameters
  • Lack of support for multithreading

Since PHP is consistently backwards compatible, PHP will still carry these burdens and strive forward.

The prejudice of the ignorant

PHP does have all sorts of problems as mentioned above, but the PHP community and PHP developers have been working on it. However, there are ignorant people who have never really understood PHP or even used it, and it is frustrating to conclude that PHP is a bad language just based on the comments on some community forums. Even one of my older mobile colleagues still thinks that the variable name in PHP is var.

Norm or norm

There are no rules, there is no circle, the society is like this, the team is like this, and the project is like this.

From a very young age, our parents began to teach us what we could and could not do. For example, "wash your hands before eating" and "don't make loud noises in public". When we enter the school and even enter the society, we understand that there are always various rules and regulations that bind us, whether it is organizational, moral, or legal. If we want to be a person who is respected by others and recognized by society, we must adhere to these norms.

There is no such thing as perfection in the world, and even the best norms are not perfect. Good norms can reduce the cost of collaboration between people, but at the same time, it will hinder flexibility, and how to grasp the degree of normative constraints is worth scrutinizing.

Before the PSR specification, there was no unified standard for code naming, file naming, and automatic loading, and each project was self-specifying or in a non-normative state. Later, PHPFIG developed the PSR specification in order to enable interoperability of components and to provide specifications for best programming and testing practices. The members of PHPFIG include many well-known open source project authors, such as CakePHP authors, Composer authors, Drupal authors, Phalcon authors, Symfony authors, Yii authors, etc. PSR is not an official specification, but many well-known open source project authors have been involved in developing the de facto specification that has made it a PHP project.

There are currently 9 implemented specifications for PSR specifications, 8 specifications in the draft stage, and 1 specification for deprecation, making a total of 18 specifications. Here are the specifications in alphabetical order:

  • PSR-0 Autoload Specification (Deprecated)
  • PSR-1 Basic Coding Specification (Implemented)
  • PSR-2 Coding Style Guide (Implemented)
  • PSR-3 Logging Interface (Implemented)
  • PSR-4 Autoload Specification (Implemented)
  • PSR-5 PHPDOC标准 (草案)
  • PSR-6 Cache Interface (Implemented)
  • PSR-7 HTTP Message Interface (Implemented)
  • PSR-8 Hug Interface (Draft)
  • PSR-9 Security Notice (Draft)
  • PSR-10 Safety Reporting Process (Draft)
  • PSR-11 Container Interface (Implemented)
  • PSR-12 Extended Coding Style Guide (Draft)
  • PSR-13 Hypermedia Link (Implemented)
  • PSR-14 Event Manager (Draft)
  • PSR-15 HTTP中间件 (草案)
  • PSR-16 Simple Caching (Implemented)
  • PSR-17 HTTP工厂 (草案)

Due to space limitations, only the implemented norms will be covered

Specifications that have been implemented

PSR-1 Basic Coding Specification

PSR-1 only regulates files, classes, and methods.

  • The file must only use <?php or <?=
  • The file must be without BOMUTF-8 encoding
  • The file should not be used to declare classes, methods, constants, etc., or to generate output, change .ini settings, etc
  • Namespaces and classes must comply with PSR-4 (PSR-0 is deprecated)
  • The naming format of the class name must be a large hump, e.g. MyClass
  • The name format of the constant must be uppercase + underscore link, for example, MY_CONSTANTS
  • The method must be named in a small hump format, e.g. myFunction

PSR-2 Coding Style Guide

PSR-2 is an extension of PSR-1 by regulating indentation, character limits, spaces, blank lines, and the visibility of classes and methods.

  • The code must comply with the PSR-1 specification
  • The indentation must be four spaces, not TAB
  • There is no hard limit on the number of characters on a line, but there is a soft limit of 120 characters. It is recommended to be less than 80 characters.
  • A blank line must be inserted after each namespace namespace declaration and use declaration block. Here are some examples:
namespace Vendor\Package;

use FooInterface;
use BarClass as Bar;
use OtherVendor\OtherPackage\BazClass;           
  • The opening curly brace of the class must also be written on its own line after the function declaration, and the closing curly brace must also be written on its own line after the body of the function. Here are some examples:
//class declare
class Foo 
{
	//class body 
}           
  • The opening curly brace of the method {must be on its own line after the method declaration, and the closing curly brace} must also be written on its own line after the body of the method. Here are some examples:
class Foo 
{
	//method declare
    public function sampleMethod($a, $b = null)
    {
		//method body
    }
    
}           
  • The properties and methods of the class must be declared before the access modifier (private, protected, and public), abstract and final must be declared before the access modifier, and static must be declared after the access modifier. Here are some examples:
<?php
class Foo 
{
	//属性前必须添加修饰符(private,protected,public)
	private $sampleProperty; 
	
	//方法前必须添加修饰符(private,protected,public)
    public function sampleMethod($a, $b = null)
    {
    }
	
	//abstract必须在访问修饰符前面
	abstract public function sampleAbstractMethod();
	
	//static必须声明在访问修饰符后面
    final public static function sampleFinalStaticMethod()
    {
    }
}           
  • There must be a space after the keyword that controls the structure, and it must not be when a method or function is called. Here are some examples:
  • The opening curly brace for the control structure must be written on the same line as the declaration, and the closing curly brace must be written on its own line after the body. Here are some examples:
  • There must be no spaces before the opening (after and closing closing parentheses) of the control structure. Here are some examples:
class Foo
{
    public function sampleMethod($a, $b = null)
    {
        if ($a === $b) {
            bar();
        } elseif ($a > $b) {
            $foo->bar($arg1);
        } else {
            BazClass::bar($arg2, $arg3);
        }
    }           

PSR-3 log interface

PSR-3 defines a generic logging interface, which allows the logging library to log information by receiving a Psr\Log\LoggerInterface object in a simple and generic way.

Implemented the class library of the PSR-3 specification

  • monologue

PSR-4 auto-load specification

PSR-4 defines a specification for the automatic loading of corresponding classes by file paths.

  • The term "class" here refers to all class classes, interfaces, traits reusable code blocks, and other similar structures.
  • A complete class name needs to be <命名空间名><子命名空间名>in the format \(\)*\<类名>. The full class name must have a top-level namespace, called a "vendor namespace", the full class name can have one or more sub-namespaces, the full class name must have a final class name, the descending line in any part of the complete class name has no special meaning, the complete class name can be composed of arbitrary uppercase and lowercase letters, and all class names must be case-sensitive
  • When loading a file with a complete class name, remove the first namespace separator, and use one or more successive namespaces and sub-namespaces as the "namespace prefix", which must correspond to at least one "file base directory", and the sub-namespace after the namespace prefix must match the corresponding "file base directory", where the namespace separator will be used as the directory separator, and the class name at the end of the separator must be the corresponding .php Implementations of autoloaders with the same name as files with suffixes must not throw exceptions, trigger error messages at any level, and have no return value

example

The following table shows the file paths corresponding to the full class name, namespace prefix, and file base directory that meet the specification.

Full class name Namespace prefix Base directory File path
\Acme\Log\Writer\File_Writer Acme\Log\Writer ./acme-log-writer/lib/ ./acme-log-writer/lib/File_Writer.php
\Aura\Web\Response\Status Aura\Web /path/to/aura-web/src/ /path/to/aura-web/src/Response/Status.php
\Symfony\Core\Request Symfony\Core ./vendor/Symfony/Core/ ./vendor/Symfony/Core/Request.php
\Zend\Acl Zend /usr/includes/Zend/ /usr/includes/Zend/Acl.php

For the implementation of this specification, please refer to relevant examples

PSR-6 cache interface

Caching is a common way to improve the performance of a project, and it is also a regular feature of most frameworks or libraries. This results in different frameworks or class inventories at different levels for caching solutions. This discrepancy forces developers to learn multiple systems that don't even provide them with the functionality they need. In addition, developers of caching libraries are faced with a choice: whether to support only a few frameworks, or to write a large number of adapters to adapt to a wide variety of systems.

PSR-6 will solve this problem, and library and framework developers can count on the caching system to work as intended, while the developer of the caching system will only need to implement a set of interfaces, rather than a full adapter.

PSR-7 HTTP消息接口

HTTP messages are the foundation of web development. Web browsers and HTTP clients such as cURL create HTTP request messages that are sent to the web server, which provides HTTP response messages. The server-side code receives the HTTP request message and returns an HTTP response message.

HTTP messages are often abstracted from the end user, but as developers, we often need to know how they are constructed and how to access or manipulate them to perform our tasks, whether it's for HTTP API requests, or for handling incoming requests.

Each HTTP request message has a specific form:

POST /path HTTP/1.1
Host: example.com

foo=bar&baz=bat
           

The first line of the request body is the "request line", which contains the HTTP request method, the HTTP request destination address (usually an absolute URL or the path of the web server), and the HTTP protocol version number. Next is one or more HTTP headers, a blank line with the message content.

HTTP response content has a similar structure

HTTP/1.1 200 OK
Content-Type: text/plain

This is the response body
           

The first line is the "status line", which contains the HTTP protocol version number, the HTTP status code and a "reason phrase" describing the status code, similar to the request message, followed by one or more HTTP headers, and a blank line with the message content.

The PSR-7 specification is an abstraction of HTTP messages and the elements that make them up.

The class library of PSR-7 was implemented

  • guzzlehttp/psr7:
  • oscarotero/psr7-middlewares
  • zendframework/zend-diactoros

PSR-11 container interface

PSR-11 is a generic interface for dependency injection containers, designed to standardize frameworks or libraries to obtain objects and parameters through containers.

Implemented the class library of PSR-11

  • PHP-IN/PHP-DI

PSR-13 hypermedia link

WHETHER IT'S HTML CONTENT OR CONTENT IN DIFFERENT API FORMATS, HYPERMEDIA LINKS ARE INCREASINGLY BECOMING AN IMPORTANT PART OF THE WEB. However, there is no single universal hypermedia format, nor is there a universal way to represent links between formats.

PSR-13 is designed to provide PHP developers with a simple, versatile, and independent way to represent hypermedia links in a serialized format that is used independently. This, in turn, allows the system to serialize the response of hypermedia links into one or more wired formats, independent of the process of deciding what those links should be.

PSR-16 Simple Cache

PSR-16 is designed to standardize a simple but extensible interface for caching entries and cache drivers.

Too much of the pain of framing

Since there is a language war, it is also a matter of course that PHP has too many frameworks as a language focused on the web domain. Do you sometimes find it frustrating to learn a framework that you can't finish?

Let's take a look at the major frameworks (in descending order of Github Star)

Laravel

Laravel is one of the hottest frameworks in PHP languages out there. With elegance as the goal, it uses a lot of new features of PHP, an active community, and a rich ecological environment. The latest LTS Laravel 5.5 already requires that the environment must be at least php 7.0. It's arguably the most stylish framework in the PHP world.

Symfony

Symfony is Papa's framework, the most powerful PHP framework. Many well-known open source projects are based on Symfony, such as Laravel, Drupal, PHPBB. Symfony's componentization coupling is very small, and you can use a single component in your project.

CodeIgniter

CI is an old PHP framework, which is easy to use, and the documentation and cases are very rich. But it is not rich enough in terms of features, and does not support too many new PHP features.

Yii2

Yii2 is a full-stack MVC framework with very good performance and scalability.

Phalcon

Phalcon is the fastest MVC framework in the PHP world, developed in the form of a Zend Extension. However, because PHP development is too black box and difficult to develop, the Phalcon team has developed another language Zephir to write Phalcon, so you can try it.

Slim

Slim is a small and well-rounded framework, and it is highly recommended for beginners to research its source code. If you're writing a small project, Slim is very handy.

Cakephp

CakePHP is not used too many people in China, but this does not affect its status as an established framework.

Lumen

Lumen is a framework focused on building microservices architectures and API applications.

In addition to the above frameworks, there are also Brother Bird's Yaf, the domestic ThinkPHP and PHP's official Zend Framework are also relatively well-known.

Generic components

Request

Since it is an HTTP project, the Request component is definitely indispensable, which encapsulates the HTTP information of the request.

Related open-source components

  • Requests

Response

Ditto, an integral component of an HTTP project, encapsulates the HTTP information of the response.

Router

The Router component is used for route distribution, finds the corresponding controller through the regular matching URL, instantiates the controller, and executes it.

Related open-source components

  • FastRoute
  • klein

Controller

The controller component is used to process business logic and interact with the Model component or View component.

Model

PHP models are generally congestion models, and the Modle component encapsulates the specific business model logic and implements the ORM, shielding the SQL details, allowing developers to manipulate the database like an operational object.

Related open-source components

  • doctrine2
  • laravel-mongodb
  • Propel2

View

The View component is typically a templating engine.

Related open-source components

  • Twig
  • smarty

ErrorHander

The ErrorHander component is mainly used to capture exceptions and error messages and handle related information.

Related open-source components

  • collision

IOC Container

IOC Containers resolve dependencies between classes through reflection.

Related open-source components

  • PHP-DI

It's a shame to have no notes

When you enter a new company, or participate in a new project, do you struggle with the fact that the project has no annotations?

I once asked a senior in the company, why don't you comment the code? Without judging the accuracy of the senior's sentence, I can only spread my hands in the face of the pasta code written by the senior.

In this section, we'll explore whether or not to write annotations, what annotations do, and how to use PHPDoc in PHP projects.

Do you want to write a note?

There are three arguments for those who are reluctant to write notes:

  • Good code doesn't need to be commented
  • Bad annotations can mislead readers
  • Writing comments takes too much time

For the first rhetoric, it is actually to emphasize the self-explanatory nature of the code, and good code will speak for itself. Then this self-description only emphasizes the logic of the code, but does not include any more information (as explained in the comment types below). Second, this statement is more of an excuse for most developers who don't write exact, concise, self-explanatory code well.

For the second argument, it emphasizes the dangers of wrong comments and believes that comments should not be written, which is like not working hard because you may not be able to do so.

For the third argument, it is emphasized that the cost of writing annotations is too high, but it is obviously worth it compared to the communication cost of not writing annotations, and the time and effort cost of re-reading comprehension.

The role of annotations

Comments are not just used to explain the code, they have other functions, here are a few of them:

Duplicate code

Repetitive comments simply describe the code in different words, and do not provide more useful information other than to increase the reader's reading.

Interpret the code

Explanatory comments are often used to explain complex, ambiguous blocks of code. The value of such comments is usually due to the ambiguity of the code. If the code needs to be explained because it is complex, the best way is to improve the code, which is what the predecessors said, "good code does not need to be commented".

Code tags

Markup comments are not intended to remain in the code, they are meant to inform developers that some work has not been done. For example: //todo.

Overview code

Summarizing code is summarizing several lines of code in one or two sentences, because the reader must read the comments faster than the code. Comments of an overview nature are useful for those who want to modify your code.

A description of the intent of the code

A purposive comment is used to indicate the intent of a piece of code, and it indicates the problem to be solved, not the solution.

Convey information that the code can't say

Some information cannot be represented in code, but must be included in the source code. Such annotations include:

  • Miscellaneous information such as copyright notice, version number, author, etc
  • Considerations for code design
  • Reference Links
  • Editors such as PHPDoc, JavaDoc, JsDoc, etc. require comments

For code as built, only three types of comments are allowed: information that the code cannot express, purposive comments, and summary comments.

The use of PHPDoc in PHP projects

PHPDoc (PSR-5) is intended to convey information that cannot be expressed by code, as described in the previous section.

@author

@author tag is used to indicate the author

grammar

@author [name] [<email address>]           

description

This @author is used to indicate who created the structural element (i.e., files, classes, interfaces, properties, methods, functions, constants, variables) or made important changes to it. This tag can also contain email addresses.

example

/**
 * @author My Name
 * @author My Name <[email protected]>
 */           

@copyright

This @copyright tag is used to record the copyright information of the structural elements

grammar

@copyright <description>           

description

@copyright defines who owns the copyright information for the "structural element", and unless otherwise indicated, the copyright of the use of this mark applies to the "structural element" to which it is applied and its children.

The format of the description is controlled by the coding standard for each project. It was proposed to refer to copyright and the year covered by the organization involved.

example

/**
 * @copyright 1997-2005 The PHP Group
 */           

@deprecated

@deprecated tags are used to indicate which "structural elements" are deprecated and removed in a later release.

grammar

@deprecated [<"Semantic Version">][:<"Semantic Version">] [<description>]           

description

@deprecated declares that the relevant "structural element" will be removed in a future release because it is obsolete or deprecated for its usage. This tag can specify two version numbers within the version number range: The first version number is called the "starting version", which indicates the version of the element in question that has been deprecated. The second version number is called the "end version", and it indicates the version of the associated element that is planned to be deprecated.

If an End Version has been specified, the related Structure Element may no longer exist in the End Version and may be removed in that version or a subsequent version, but must be present in all previous versions.

It is recommended that you specify both the Start Version and the End Version. In this case, the two version numbers must be separated by a colon (:) with no spaces in between. "Start Version" may be omitted. In this case, the "end version" must have a colon.

This markup may provide an additional description of why the associated element is deprecated.

If the associated element is replaced by another element, it is recommended to add a @see to the "PHPDoc" that points to the new element.

example

/**
 * @deprecated
 *
 * @deprecated 1.0.0:2.0.0
 * @see \New\Recommended::method()
 *
 * @deprecated 1.0.0
 *
 * @deprecated :2.0.0
 *
 * @deprecated No longer used by internal code and not recommended.
 *
 * @deprecated 1.0.0 No longer used by internal code and not recommended.
 */           

@method

@method allows a class to know which "magic" methods are callable.

grammar

@method [return type] [name]([type] [parameter], [...]) [description]           

description

@method markup is used in cases where the class contains __call() magic methods and defines some explicit purpose.

There is a child class whose parent class has a __call() to have dynamic getters or setters to predefined properties. The child class knows which getters and setters need to exist, but relies on the parent class's __call() method to provide it. In this case, the subclass will use @method tag for each magic setter or getter method.

@method tags allow authors to specify the type of pass parameters and return values by including these types in the signature.

The return type can be omitted when the expected method does not have a return value, in which case the default return type is void;.

@method tags cannot be used in PHPDoc that is not associated with a class or interface.

example

class Parent
{
    public function __call()
    {
        <...>
    }
}

/**
 * @method string getString()
 * @method void setInteger(int $integer)
 * @method setString(int $integer)
 */
class Child extends Parent
{
    <...>
}           

@param

@param tags are parameters that are used to indicate a function or method

grammar

@param ["Type"] [name] [<description>]           

description

You can use the @param tag when specifying the type and function of a function or method's arguments. When provided, it must contain a "type" to indicate what is expected; on the other hand, the description is optional but recommended. For complex constructs, such as selecting arrays, it is recommended to use the "inline phpDoc" description of the array of options.

@param can have multiple lines of description and do not need to be clearly defined.

It is recommended to use this markup for every function and method.

example

/**
 * Counts the number of items in the provided array.
 *
 * @param mixed[] $items Array structure to count the elements of.
 *
 * @return int Returns the number of elements.
 */
function count(array $items)
{
    <...>
}           

The following example shows how to label an optional array with two elements: 'required' and 'label' with an 'inline phpDoc'.

/**
 * Initializes this class with the given options.
 *
 * @param array $options {
 *     @var bool   $required Whether this element is required
 *     @var string $label    The display name for this element
 * }
 */
public function __construct(array $options = array())
{
    <...>
}           

@property

@property tags are used to let a class know which "magical" properties exist.

grammar

@property ["Type"] [name] [<description>]           

description

When a class contains __get() and __set() magic methods, you can use @property to specify a specific name.

There is a child class and its parent class has a __get(). The child class knows which properties need to exist, but relies on the parent class's __get() method to get it. In this case, the subclass will write a @property tag for each magic attribute.

@property tag cannot be used in "PHPDoc" without classes or interfaces.

example

class Parent
{
    public function __get()
    {
        <...>
    }
}

/**
 * @property string $myProperty
 */
class Child extends Parent
{
    <...>
}           

@return

@return tag is used to indicate the return value of a function or method

grammar

@return <"Type"> [description]           

description

You can use @return when specifying the return value of a function or method, and when you use a @return, be sure to include "Type" to specify what type is returned, and the description on the other hand is optional, but recommended when returning complex structures such as associative arrays.

@return tags may have a multi-line description that doesn't require explicit restrictions.

It is recommended to use this tag in every function and method. The only exception to this is that functions and methods do not return a value, as defined by any of the project's coding standards: in this case@return can be omitted.

example

/**
 * @return int Indicates the number of items.
 */
function count()
{
    <...>
}

/**
 * @return string|null The label's text or null if none provided.
 */
function getLabel()
{
    <...>
}           

Writing test case development is fascinating

As the most common activity to improve the quality of a project, testing has always been an important part of project development.

The level of the test

  • Unit testing: It is the isolation of a complete class or function from the complete system for testing.
  • Integration test: It is a joint test of two or more libraries or classes. This kind of testing usually starts with two classes that can be tested, and continues until the system is developed.
  • Regression testing: This is the repetition of previous test cases in order to find defects in software that originally passed the same set of tests.
  • System Testing: It is to run the entire software in the final configuration. In order to test security, performance, resource consumption, timing issues, and other issues that cannot be tested on low-level integrations.

Why write test cases

  • Better code quality
  • Save time by avoiding repetitive tests
  • Sort out the business logic

Test first or test last

Sometimes developers are confused about whether to write test cases first or write test cases after writing the code? The answer is to test the current one, and here's why:

  • Writing a test case before writing code doesn't take longer than writing a test case after writing code.
  • Assuming you write test cases first, you'll find defects earlier and fix them earlier.
  • Writing test cases first will allow you to think about requirements and design earlier, and better write high-quality code.
  • Writing test cases before writing code can expose problems with requirements earlier.

Is it really faster to develop a project without writing test cases than it is to write a test case?

It seems that most developers are aware of the benefits of writing test cases for project development. However, the time cost is a concern for developers who are reluctant to write test cases.

So let's think about the role of writing test cases - finding a defect and fixing it, either in requirements or in specific coding. We know that the earlier a defect is discovered, the lower the cost (time and effort) of remediation. Defects in requirements are more costly than defects in coding. If you can find and fix defects in your requirements early by writing test cases, it will take far less time to find defects than when the project is about to be delivered. Compared to possible rework or re-requirements correction and evaluation, it takes less time to write test cases.

Relevant testing frameworks

PHPUnit

PHPUnit是xUnit家族的一员,更是最有名的PHP测试框架。

Behat

Behat is a BDD (Behavior Driven Testing) framework.

Codeception

Codeception is a modern full-stack testing framework based on PHPUnit. Inspired by BDD (Behavior Driven Testing), it offers a whole new way to write acceptance, functional, and even unit tests.

phpspec

phpspec is also a BDD (Behavior Driven Testing) framework.

Hello colleagues

Three stinkers can withstand one Zhuge Liang, and a small company may rely on a certain person, but if a company wants to become bigger, it must depend on whether the ability of the whole team is strong enough.

The emotional impact of the team on the individual

It's like having a safe harbor, you can work hard outside, but when you encounter problems and setbacks, the team will definitely give you mental encouragement.

The team complements the individual's ability and character

Everyone in the team has complementary skills, strengths, knowledge, age, personality, etc., and you can get a different concept through the perspective of your colleagues to make up for the shortcomings in your ability and personality.

Move towards your goal

Every team must have a goal that is both a team and an individual, and learn to trust, understand, and sacrifice on the way to this goal.

Methodology with 'X'DD

Suppose there is a person in the world who has unlimited energy, the highest efficiency, the fastest speed, and the most complete knowledge system, then he is 100% efficient in doing everything. However, there is no such person in the world, but we hope to temper the team through their own methods, so that the team's work efficiency tends to be infinitely inclined to this person.

methodology

What is the methodology?

Methodology is a theoretical system or system with the goal of solving problems, which usually involves the discussion of problem stages, tasks, tools, methods and skills. The methodology analyzes and studies a series of specific methods, systematically summarizes and finally proposes more general principles.

Methodology in software development

Software development is an engineering science, and in order to enable the team to complete a certain task more efficiently and accurately, many predecessors have proposed the following methodologies.

  • Waterfall development
  • Iterative models
  • Spiral development
  • Agile development

Waterfall development

Waterfall development is a serialized way of development. As shown in the figure below

Strive to be an excellent PHP developer

Peculiarity:

  • Each stage is independent and dependent on the previous one
  • Document-driven
  • Easy to organize, easy to manage
  • It is a strictly linear, phase-sequential, step-by-step development model

Applicable Scenarios:

  • Projects with clear product roadmaps and mature technical solutions
  • Quality is more important than development efficiency
  • When R&D capabilities are weak, it is easier to control with a waterfall development process

缺陷:

  • In the early stage of the project, the requirements are often unclear, and it is difficult to finalize the requirements at the early stage, which affects the later links
  • During the development process, a large amount of documentation needs to be generated, which increases the workload
  • Since the development model is linear, users will not see the results until the end of the process, which increases the risk of development.

Iterative models

The iterative model reduces risk by breaking down large requirements into cycles for development. As shown in the figure below, a cycle is an iteration.

Peculiarity:

  • It is not required to develop a complete software system at one time, and software development is regarded as a process of gradually obtaining wide demand and improving software products
  • Reduce risk, even if you make a mistake, you only lose the cost of an iteration cycle
  • Developers know where the problem is focused and are more productive
  • User needs don't have to be fully defined at the outset

Applicable Scenarios:

  • Projects whose requirements are difficult to determine and are constantly changing
  • Analyze projects that designers are familiar with in their field of application
  • Users can participate in the project in the development process to varying degrees

缺陷:

  • The level of managers is required

Spiral model

The spiral model is an evolutionary software development process model that combines the iterative characteristics of rapid prototyping with the systematic and rigorous monitoring of the waterfall model. The biggest feature of the spiral model is that it introduces risk analysis that other models do not have, so that the software has the opportunity to stop when major risks cannot be ruled out to reduce losses. At the same time, building prototypes at each iteration stage is a way for the spiral model to reduce risk. The spiral model is more suitable for large, expensive system-level software applications.

Peculiarity:

  • Flexibility in design, which can be changed at various stages of the project
  • Building large systems in small segments makes costing simple and easy
  • The client is always involved in every stage of development, ensuring that the project does not deviate from the right direction and that the project is controllable.
  • As the project progresses, the client is always up-to-date on the project, allowing him or her to interact effectively with management.
  • Customers appreciate the good communication and high quality of the products that result from this in-house development approach.

Applicable scenarios

  • Large, high-risk projects
  • Recently developed projects with unclear needs

Agile development

Agile development takes the evolution of user needs as the core, and adopts an iterative, step-by-step approach to software development. In agile development, a software project is divided into sub-projects at the beginning of the build, and the results of each sub-project are tested and visualized, integrated, and operational. In other words, a large project is divided into smaller projects that are interconnected but can also run independently, and completed separately, while the software remains in a usable state.

Unlike the other three models, agile development is more about articulating an attitude.

Core Principles

  • Advocate simplicity
  • Embrace change
  • Your second goal is sustainability
  • Incremental changes
  • Maximize your investment
  • Purposeful modeling
  • Multiple models
  • High-quality work
  • Quick feedback
  • Software is your main goal
  • Travel light

Principles of the Declaration

We welcome changes in requirements, even in the late stages of development. Agile processes are able to navigate change and maintain a competitive advantage for customers. Deliver working software frequently, from a few weeks to a few months, with shorter timescales the better. Business people and developers should work together throughout the project. Surround software development with motivated people and give developers the right environment to meet their needs and trust them to get the job done. The most effective and effective way to communicate information in a development group is through face-to-face conversations. Working software is the primary measure of progress. The agile process promotes sustainable development. Funders, developers, and users should always maintain the same cadence. The constant pursuit of technical excellence and good design will help to increase agility. Simplicity – the art of minimizing the amount of work is essential. The best architectures, requirements, and designs come from self-organizing teams. Every once in a while, the team takes stock of how to be more effective and then adjusts their behavior accordingly

'X'DD

This chapter explains the most common driver development.

TDD

Test-driven development is a new development method that is different from the traditional software development process. It requires that test code be written before a feature is written, and then only the feature code that makes the test pass, and the test will drive the entire development forward. This helps to write concise, usable, and high-quality code and speeds up the development process.

steps

  1. A new test has been added
  2. Run all the tests (sometimes just one or a subset of them) and find that the new test doesn't pass
  3. Make a few small changes to get the test program running as quickly as possible, and use some unconscionable methods in the program for this
  4. Run all the tests and pass them all
  5. Refactor code to eliminate duplicate designs and optimize design structure

advantage

  • TDD writes test cases according to customer needs, designs the process and interface of the function, and this design of the code from the user's perspective is usually more in line with the needs of later development. By paying attention to user feedback, we can respond to changes in needs in a timely manner, and because of the simple design from the user's point of view, we can also adapt to changes more quickly.
  • The need for ease of testing and test independence will lead to loosely coupled designs and more reliance on interfaces rather than specific classes, improving the scalability and demutability of the system. And TDD significantly shortens the feedback loop for design decisions, allowing us to get feedback within seconds or minutes.
  • Putting testing before coding, and running all tests frequently, can avoid errors as much as possible and catch them as early as possible, greatly reducing the cost of subsequent testing and fixing, and improving the quality of the code. Under the protection of testing, the code is constantly refactored to eliminate duplicate designs, optimize the design structure, improve the reusability of the code, and thus improve the quality of the software product.
  • TDD provides continuous regression testing that gives us the courage to refactor, as the tests will notify us immediately of any exceptions to other parts of the system caused by changes to the code. Full testing helps us keep track of the status of the entire system, so we don't have to worry about unpredictable side effects.
  • The unit test code generated by TDD is the perfect developer documentation, showing how all the APIs should be used and how they work, and they are always up-to-date with the working code.
  • TDD reduces stress, reduces anxiety, increases our confidence in the code, and gives us the courage to refactor, which are all important prerequisites for happy work.
  • Quickly improve the development efficiency

Relevant PHP testing frameworks

  • phpunit

BDD

Behavior Driven Development is an agile software development technique that encourages collaboration between developers, QAs, and non-technical or business participants in software projects. BDD was originally named by Dan North in 2003 and includes the practice of extreme programming such as acceptance testing and customer test driven, as a response to test-driven development.

Unlike TDD, BDD does not use test cases to discipline developers to write higher-quality code with fewer bugs, but focuses more on behavioral design to solve the problem of disconnect between requirements and development.

steps

  1. The demand side defines the story
  2. Develop and write specific code
  3. The demand-side checks whether the behavior matches the story
  4. Code refactoring and optimization

merit

  • Avoid the communication barriers between the demander and the developer, and realize that the customer and the developer can define the requirements of the system at the same time
  • It can ensure that the developed product is more in line with the needs
  • Shorten the testing cycle after the end of the development phase

DDD

Domain-driven development is an approach to software development that achieves complex requirements by connecting implementations with evolving models.

The world is so big, I want to see it

The scope of computer science is huge, and as developers, we sometimes don't know how big the boundaries are. The ancients had a saying: Those who do not seek the overall situation are not enough to seek a domain. The world of computers is so big, do you want to see it?

Major areas of computer science (adherence to the ACM-2012 Computational Classification System) (By wiki)

Categories Sub-categories
Computer hardware Printed circuit boards, peripherals, integrated circuits, VLSI circuits, green computing, electronic design automation
System architecture organization Computer System Architecture: Embedded Systems Real-Time Computing
Internet Network Transport Protocols, Routing, Network Topology, Network Services
Software organization Interpreter, Middleware, Virtual Machines, Operating Systems, Software Quality
Software Symbols and Tools Programming Paradigm Programming Language Compiler Domain Specific Language Software Framework Integrated Development Environment Software Configuration Management Library
Software development Software Development Process, Requirements Analysis, Software Design, Software Deployment, Software Maintenance, Open Source Model
Theory of Computing Automata Computability Theory Computational Complexity Theory Quantum Computing Numerical Computational Methods Computer Logic Formal Semantics
algorithm Algorithm Analysis Algorithm Design Randomization Algorithm Computational Geometry
Computational Mathematics Discrete Mathematics · Probability · Statistics · Math Software · Mathematical Logic · Set Theory · Number Theory · Graph Theory · Typology · Category Theory · Information Theory · Numerical analysis · Mathematical analysis
information system Database Management System, Computer Data, Enterprise Information System, Social Software, Geographic Information System, Decision Support System, Process Control, Data Mining, Digital Library, System Platform, Digital Marketing, World Wide Web, Information Retrieval
safety Cryptography Formal Methods Intrusion Detection Systems Network Security Information Security
Interactive Computer-aided functions · User Interface · Wearable Computers · Ubiquitous Computing · Virtual Reality · Chatbots
Concurrency Concurrent Computing, Parallel Computing, Distributed Computing, Multithreading, Multi-processing
artificial intelligence Automatic Reasoning · Computational Linguistics · Computer Vision · Evolutionary Computation · Expert System · Natural Language Processing · Robotics
machine learning Supervised Learning Unsupervised Learning Reinforcement Learning Cross-validation
Computer graphics Computer Animation, Visualization, Rendering, Retouching Photos, Graphics Processors, Mixed Reality, Virtual Reality, Image Processing, Image Compression, Solid Modeling
Applied computing E-commerce Enterprise Software Computational Mathematics Computational Physics Computational Chemistry Computational Biology Computational Social Sciences Medical Informatics Digital Arts Electronic Publishing Cyber Warfare Video Games Word Processors Operations Research Educational Technology Bioinformatics Cognitive Science Document Management System

Values

The length of life is measured by time, and the value of life is measured by contribution.

Small but beautiful

Reducing complexity is at the heart of software development. The human brain doesn't have the power to manage that much detail, but we can handle this complexity with a variety of tools and ideas. Whether it is system construction or business coding, small but beautiful must be the direction of efforts.

automation

High-frequency and low-value work needs to be handed over to machines, and we need to do some high-leverage, high-value-added work.

Create the world

Why does every language start with hello world? Think about the variables you've defined, the methods you've defined, and you're specifying rules from God's point of view. Just like Minecraft, you're creating a whole new world. The only difference is that Minecraft is made with pixel blocks, and you're creating and enjoying it in a more advanced and wonderful way.

Read on