From reading the core code of Discuz and giving a comment on the experience of how the programmer should read the code?

Source: Internet
Author: User
Tags autoload diff

This article tags : programmer php discuz Core Code Framework Deep Learning Framework

Reading good code is the best way to develop technology. Remember every newcomer, I have done reading good code requirements, but almost all can only adhere to a very little time.

The night before the people are still joking about the discussion, all because of the previous look at some of the wording, only to learn some of the messy tricks.

In the evening I began to re-read the core code of Discuz, took more than 1h time to complete a core file comments.

The code after the comment:

<?php

/**

* [discuz!] (C) 2001-2099 Comsenz Inc.

* This was not a freeware, use was subject to license terms

*

* $Id: class_core.php 33982 2013-09-12 06:36:35z Hypowang $

*/

Error_reporting (E_all);

Define (' In_discuz ', true);

Define (' Discuz_root ', substr (DirName (__file__), 0,-12));

Define (' Discuz_core_debug ', false);

Define (' discuz_table_extendable ', false);

Set_exception_handler (Array (' core ', ' handleexception '));

if (discuz_core_debug) {

Set_error_handler (Array (' core ', ' handleError '));

Register_shutdown_function (Array (' core ', ' Handleshutdown '));

}

if (function_exists (' Spl_autoload_register ')) {

Spl_autoload_register (Array (' core ', ' autoload '));

} else {

function __autoload ($class)

{

Return Core::autoload ($class);

}

}

C::creatapp ();

/**

* Discuz Frame Entry class

*/

Class Core

{

/**

*

* @var Array to stage all instantiated table objects

*/

private static $_tables;

/**

*

* @var array staging current to load class path mapping relationship

*/

private static $_imports;

/**

*

* @var discuz_application Application Instance Object

*/

private static $_app;

/**

*

* @var Discuz_memory

*/

private static $_memory;

/**

* Get a single Application object

* @return Discuz_application

*/

public static function app ()

{

return Self::$_app;

}

/**

* Create global Singleton Application object

* @return Discuz_application

*/

public static function Creatapp ()

{

if (!is_object (Self::$_app)) {

Self::$_app = Discuz_application::instance ();

}

return Self::$_app;

}

/**

* Create a Table object for the Discuz system

* @param string $name

* @return Discuz_table

*/

public static function T ($name)

{

Return Self::_make_obj ($name, ' table ', discuz_table_extendable);

}

/**

* Create Model objects under the Discuz system

* @param string $name

* @return Discuz_model

*/

public static function M ($name)

{

$args = Array ();

if (Func_num_args () > 1) {

$args = Func_get_args ();

unset ($args [0]);

}

Return Self::_make_obj ($name, ' model ', true, $args);

}

/**

* Create an object instance

* @param string $name class ID, format "# $pluginid # $name"

* @param string $type represents the namespace, supports only one level, and the file name is prefixed with this level

* @param boolean $extendable dedicated to table classes

* @param array $p data that is specific to the table class, passed to the constructor method parameter of the class

* @return Mixed

*/

protected static function _make_obj ($name, $type, $extendable = false, $p = Array ())

{

$pluginid = null;

if ($name [0] = = = = ' # ') {

List (, $pluginid, $name) = Explode (' # ', $name);

}

$cname = $type. ‘_‘ . $name;

if (!isset (self::$_tables[$cname])) {

if (!class_exists ($cname, false)) {

Self::import ($pluginid? ' plugin/'. $pluginid: ' class '). ‘/‘ . $type. ‘/‘ . $NAME);

}

if ($extendable) {

self::$_tables[$cname] = new Discuz_container ();

Switch (count ($p)) {

Case 0:self::$_tables[$cname]->obj = new $cname ();

Break

Case 1:self::$_tables[$cname]->obj = new $cname ($p [1]);

Break

Case 2:self::$_tables[$cname]->obj = new $cname ($p [1], $p [2]);

Break

Case 3:self::$_tables[$cname]->obj = new $cname ($p [1], $p [2], $p [3]);

Break

Case 4:self::$_tables[$cname]->obj = new $cname ($p [1], $p [2], $p [3], $p [4]);

Break

Case 5:self::$_tables[$cname]->obj = new $cname ($p [1], $p [2], $p [3], $p [4], $p [5]);

Break

Default: $ref = new Reflectionclass ($cname);

self::$_tables[$cname]->obj = $ref->newinstanceargs ($p);

Unset ($REF);

Break

}

} else {

self::$_tables[$cname] = new $cname ();

}

}

return self::$_tables[$cname];

}

/**

* Get global Cache Processing object instance

* @return Discuz_memory

*/

public static function memory ()

{

if (!self::$_memory) {

Self::$_memory = new Discuz_memory ();

Self::$_memory->init (Self::app ()->config[' memory ');

}

return self::$_memory;

}

/**

* Manually import the class library under the Discuz system

* @param string $name file name in file name if it contains/, the file name is automatically prefixed with the upper namespace prefix, such as ' Abc/edf/hi ' corresponding files ' abc/edf/edf_hi.php '

* @param string $folder relative to the directory name in the/source/directory

* @param boolean $force True to indicate that the import must succeed; False to return false on behalf of import failure; default true

* @return Boolean import results

* @throws Exception $force parameter is true, throws an exception if the import fails

*/

public static function Import ($name, $folder = ", $force = True)

{

$key = $folder. $name;

if (!isset (self::$_imports[$key])) {

$path = Discuz_root. '/source/'. $folder;

if (Strpos ($name, '/')!== false) {

$pre = basename (dirname ($name));

$filename = DirName ($name). ‘/‘ . $pre. ‘_‘ . BaseName ($name). '. php ';

} else {

$filename = $name. '. php ';

}

if (Is_file ($path. ‘/‘ . $filename)) {

Include $path. ‘/‘ . $filename;

self::$_imports[$key] = true;

return true;

} elseif (! $force) {

return false;

} else {

throw new Exception (' oops! System file lost: '. $FILENAME);

}

}

return true;

}

public static function HandleException ($exception)

{

Discuz_error::exception_error ($exception);

}

public static function HandleError ($errno, $errstr, $errfile, $errline)

{

if ($errno & Discuz_core_debug) {

Discuz_error::system_error ($errstr, False, True, false);

}

}

public static function Handleshutdown ()

{

if ($error = Error_get_last ()) && $error [' type '] & Discuz_core_debug) {

Discuz_error::system_error ($error [' message '], False, true, false);

}

}

/**

* Used to register the automatic loading rules of the DISCUZ framework (source/class/) class to PHP

*

* The DISCUZ Framework's automatic loading specification does not follow PSR-0, nor does it follow PSR-4, and there is no complete vendor identity concept.

* Due to the case of PHP bottom-level classification name, and will be uniformly converted to lowercase, so discuz according to this principle, provisions:

* 1. All class names and namespace sections are lowercase, and the corresponding filenames and directory names are also forced to lowercase to match;

* At the same time, the class file name takes the part of the first level namespace,

* such as discuz_application (when we write, in order to maintain a consistent style with other frames,

* can be written as discuz_application, can also be used normally) class corresponding file

* source/class/discuz/application.php;

* 2. Discuz even advocates the use of a first-level namespace.

*

* @param string $class

* @return Boolean load succeeds, returns true unless the class does not exist when the class_exists (' Class_1 ', true) function is manually invoked to return false;

* Otherwise, when the class fails to load, output an error message and terminate the program

* @see Core::import ()

*/

public static function AutoLoad ($class)

{

$class = Strtolower ($class);

if (Strpos ($class, ' _ ')!== false) {

List ($folder) = Explode (' _ ', $class);

$file = ' class/'. $folder. ‘/‘ . substr ($class, strlen ($folder) + 1);

} else {

$file = ' class/'. $class;

}

try {

Self::import ($file);

return true;

} catch (Exception $exc) {

$trace = $exc->gettrace ();

foreach ($trace as $log) {

if (Empty ($log [' class ']) && $log [' function '] = = ' class_exists ') {

return false;

}

}

Discuz_error::exception_error ($EXC);

}

}

/**

* Turn on performance analysis

* @param string $name trace identity, named format "#分组 # identity Name" or "Identity name"

*/

public static function Analysisstart ($name)

{

$key = ' other ';

if ($name [0] = = = = ' # ') {

List (, $key, $name) = Explode (' # ', $name);

}

if (!isset ($_env[' analysis ')) {

$_env[' analysis '] = array ();

}

if (!isset ($_env[' analysis '] [$key])) {

$_env[' analysis ' [$key] = array ();

$_env[' analysis ' [$key] [' sum '] = 0;

}

$_env[' analysis ' [$key] [$name] [' start '] = Microtime (TRUE);

$_env[' analysis ' [$key] [$name] [' start_memory_get_usage '] = Memory_get_usage ();

$_env[' analysis ' [$key] [$name] [' start_memory_get_real_usage '] = Memory_get_usage (true);

$_env[' analysis ' [$key] [$name] [' start_memory_get_peak_usage '] = Memory_get_peak_usage ();

$_env[' analysis ' [$key] [$name] [' start_memory_get_peak_real_usage '] = Memory_get_peak_usage (true);

}

/**

* Stop Performance analysis

* @param string $name Trace identity format is the same as the Open method parameter

* @return Array returns the contents of the performance parameter for the specified identity, in the format:

* [

* Time =,

* Stop_memory_get_usage =,

* Stop_memory_get_real_usage =,

* Stop_memory_get_peak_usage =,

* Stop_memory_get_peak_real_usage =

* ]

*/

public static function Analysisstop ($name)

{

$key = ' other ';

if ($name [0] = = = = ' # ') {

List (, $key, $name) = Explode (' # ', $name);

}

if (Isset ($_env[' analysis ' [$key] [$name] [' start ']) {

$diff = Round ((Microtime (TRUE)-$_env[' analysis ' [$key] [$name] [' Start ']) * 1000, 5);

$_env[' analysis ' [$key] [$name] [' time '] = $diff;

$_env[' analysis ' [$key] [' sum '] = $_env[' analysis ' [$key] [' Sum '] + $diff;

unset ($_env[' analysis ' [$key] [$name] [' Start ']);

$_env[' analysis ' [$key] [$name] [' stop_memory_get_usage '] = Memory_get_usage ();

$_env[' analysis ' [$key] [$name] [' stop_memory_get_real_usage '] = Memory_get_usage (true);

$_env[' analysis ' [$key] [$name] [' stop_memory_get_peak_usage '] = Memory_get_peak_usage ();

$_env[' analysis ' [$key] [$name] [' stop_memory_get_peak_real_usage '] = Memory_get_peak_usage (true);

}

return $_env[' analysis ' [$key] [$name];

}

}

/**

* Frame entry class, core class name shorthand

* @see Core

*/

Class C extends Core

{

}

/**

* DB Access object, mainly using its static method class name shorthand

* @see Discuz_database

*/

Class DB extends Discuz_database

{

}

For this kind of framework code, unfamiliar words, because there are too many involved, may feel impossible. Therefore, the general is to spend a little more time, figure out the directory structure of the code, to understand the chest.

Next, organize the dependencies between files, preferably organized into separate text, to help the brain form an intuitive impression.

Then find the entrance file, from the least dependent part of the view, the more the library type, the less dependent on things, but the one or two Lib see after the moment there is no need to watch. You still have to look at the frame entry and figure out how the framework works and the loading process. Our brains are gray, the thinking is not so clear, this process, also need to help note.

Make as many comments as possible, from the meaning of each class, the functions that it contains, the return value type of each method's parameters, the use of the method, the principle of implementation, and so on, by annotating the text, restoring the code author's thoughts, and then absorbing the thought into his own.

Determine whether you will read the basic criteria of the code, whether you can annotate the code clearly, no longer need additional auxiliary documents. Because, from the point of view of the technician, the annotated document in the code is available through tools such as Phpdoc to generate API documentation, with a variety of functions relative to one thing. If you can't write code or read code, you need to be aware of the clarity and purpose of the program.

This article source: http://www.cnblogs.com/x3d/

written at the end: for Freedom look outside the world, as well as it this line, not to go to Google data, finally, Amway a V--PN agent. a red apricot accelerator , go to Google data is the absolute first choice, the connection speed, the use is also convenient. I bought is 99¥ a year, through this link (http://my.yizhihongxing.com/aff.php?aff=2509) registration after the payment of the coupon code WH80, divided down, only 7 yuan per month, special benefits.

This article tags : programmer php discuz Core Code Framework deep Learning Framework

Turn from SUN's BLOG-focus on Internet knowledge, share the spirit of the Internet!

Original Address: " from reading the core code of Discuz and giving a comment on the experience of how the programmer should read the code? " "

Related reading : TensorFlow "machine learning": understanding and implementation of fast neural style "quick stylized images"

related reading:" I am a G powder, has been concerned about Google, recently Google has some little gestures, probably a lot of people do not understand "

related reading:" machine learning leads to technological innovation in the field of cognition, so how can the SaaS industry be changed by machine learning?" "

related reading:"VPS Tutorial Series: DNSMASQ + DNSCrypt + SNI Proxy smooth access to Google configuration tutorial "

Related reading: useful for programmers: 2017 latest in Google's Hosts file download and summary of the various hosts encountered the problem of the solution and configuration of the detailed

Related reading: Aaron swartz– The internet genius of the life course: every moment asked himself, now the world what is the most important thing I can participate in doing? "
Related reading: " site environment Apache + PHP + mysql xampp, how to implement a server on the configuration of multiple sites?" "

Related reading: What is the engineer culture? Why are the engineers alive? As an IT or internet company Why should the engineer text

related reading: the Win10 perpetual activation tutorial and how can I see if the Windows system is permanently activated? 》

Related blog:SUN ' S blog -Focus on Internet knowledge and share the spirit of Internet! Go and see:www.whosmall.com

Original address: http://whosmall.com/?post=276

From reading the core code of Discuz and giving a comment on the experience of how the programmer should read the code?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.