语言和开发规则

Revision as of 06:08, 15 September 2023 by ShengGang (talk | contribs)


以下是我们在Dolibarr项目中使用的开发语言、语法和开发标准的一些规则:

版本管理

  • Dolibarr 必须适用于:
  1. 所有操作系统(Windows, Linux, MACOS...)
  2. PHP 7.1.0+(需要DateTimeZone.getOffset、php-intl等函数)(除了数据库访问模块之外,必须可以在没有任何PHP扩展模块的情况下运行)。
  3. Mysql 5.7.7+

规范版权声明

  • 所有 PHP 文件必须以如下所示的标题开头。
<?php
/* Copyright (C) YYYY John Doe  <email@email.com>
 *
 * Licence information
 */
...

当编辑项目的现有文件时,必须在他人的版权行下添加自己的版权行。

规范 PHP 代码

PHP

  • Dolibarr 是用PHP编写的,支持所有高于 7.1.0+的 PHP 版本(需要 DateTimeZone.getOffset、 php-intl等函数)。 所有文件的扩展名必须为 .php
  • 对PHP超全局变量的调用必须通过专用运算符,如:$_COOKIES、$_SERVER、$_ENV。但是要获取$_GET或$_POST的内容,必须使用 Dolibarr 函数 GETPOST() 或 GETPOSTINT() 。

在PHP中被弃用的其他运算符($HTTP-SERVER-GET,…)不能再使用。因此,即使选项 register-long-arrays 设置为off,代码也必须能正常工作。此外,当PHP选项 register-globals 设置为off(PHP推荐)或 register-globals 设置为on(许多安装的默认设置)时,代码也必须能正常工作。

  • 请勿使用 PHP_SELF,请改用 $_SERVER["PHP_SELF"]。此外,Dolibarr框架调用了一个例程,以使$_SERVER["PHP_SELF"]的内容更安全(在main.inc.php文件中,因此是在任何业务处理之前)
  • 当多个变量必须初始化为相同的值时,必须使用多个单独的声明(由;分隔)语句:
$var1=1;$var2=1;$var3=1;

而不是

$var1=$var2=$var3=1;

后一种情况下更慢。

其效率较低。

  • 字符串中调用变量时,变量必须在引号之外。
print 'My text show my '.$variable.' !';
  • 注释必须遵循C语法,即对单行注释使用双斜杠,对代码块注释使用斜杠星号。
/* 块注释
 *
 * 块注释结束
 */

$monobjet = new MonObjet($db);
$result=$monobjet->fetch($idobject);

for ($i = 1 , $i < 2 ; $i++)
{
  // 单行注释
  print $i;
}
  • 函数必须在成功时返回大于等于0的数字,在错误时返回小于0的数字。
  • Dolibarr核心代码中没有死代码(不被使用)(仅由外部模块使用的代码必须包含在外部模块中)。
  • 使用"include_once"加载任何包含函数或类定义的文件(如 *.class.php 和 *.lib.php),使用 "include"加载任何模板文件或包含HTML和PHP混合代码的文件(如 *.inc.php 和 *.tpl.php)。
  • 要使用的编码风格是PSR-12 (https://www.php-fig.org/psr/psr-12/)。仅强制执行“必须”的规则。另请注意以下要点/例外:
    • 行的长度:PSR-12规定行长度的“软”限制为120个字符。事实上,最好是用长行声明数据而不是长页面,因为该代码不包含任何有趣或有用的逻辑,但“硬”限制为1000个字符。超出此范围的代码将导致集成平台的持续报错。
    • 允许使用制表符:另一个例外是我们没有系统地用空格替换制表符。使用制表符对大多数编辑器/开发人员来说更为方便。此外,使用空格也会破坏某些自动格式化功能(如某些版本的Eclipse的自动格式化功能)。目前,最好的设置是“保持空格/制表符不变”,但是,您可以启用“删除行尾的空格”选项。
    • 注意 1:遵循以下规则尤为重要:
      • 文件必须用Unix格式(LF)保存,而不是Windows(CR/LF)格式。Unix格式兼容所有操作系统,如Unix、Windows、Mac,但是Windows文本文件格式在Unix下的某些PHP中会出现问题。
      • 不要使用PHP智能标签。PHP代码部分必须以 <?php 开头
    • 注意 2:您可以使用文件 dev/setup/codesniffer/ruleset.xml 作为规则文件,使用 PHPCodeSniffer 检查代码规范。
    • 注意 3:您可以使用文件 dev/setup/eclipse/PSR-12 [built-in].xml 作为规则文件来配置 Eclipse 的语法格式化。
    • 注意 4:您会注意到,当前代码不一定遵循所有这些规则。原因是历史性的。这条规则是在这个过程中制定的,所以如果你发现任何代码不符合这个标准,不要犹豫,纠正它。(请记住2个例外)。

类和属性结构

在不同的类中有一些相同的属性。为了避免使用不同的名称,我们将使用以下PHP属性名称:

- entity                         that is id for the multicompany feature
- date_creation:                 date of creation
- date_modification:             date of last modification (often field tms in database)
- date_validation:               date validation
- fk_user_creation:              id of User of creation
- fk_user_modification:          id of User of last modification
- fk_user_validation:            id of User of validation
- import_key                     contains the import code YYYYMMDDHHMMSS, if record was loaded with a mass import.

- entity 多公司功能的ID

- date_creation: 创建日期

- date_modification: 上次修改日期(通常是数据库中的tms)

- date_validation: 确认日期/验证日期

- fk_user_creation: 创建者的ID

- fk_user_modification: 上次修改者的ID

- fk_user_validation: 确认者/验证者的ID

- import_key 如果记录是用批量导入加载的,则存放导入编号 YYYYMMDDHHMMSS 。

规范 SQL

DDL 文件格式

每张表必须有两个包含数据库结构定义(DDL)的文件。

  • 第一个文件定义表及其字段。文件名包含表名,例如:llx_mytable.sql

还将为每个字段添加注释以解释其含义。

  • 第二个文件定义所有外键、性能索引或其他唯一性约束,文件名类似于:llx_mytable.key.sql。

对于所有标准模块,这些文件必须存储在目录 install/mysql/tables 中;对于外部模块,这些文件必须存储在目录 mymodule/tables 中。

示例:用于创建表 llx_mytable 的文件 llx_mytable.sql

-- ===========================================================================
-- Copyright (C) 2013 Author <email@author.com>
-- 
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
-- ===========================================================================

create table llx_mytable
(
  rowid       integer NOT NULL AUTO_INCREMENT PRIMARY KEY,
  ref	      varchar(30)       NOT NULL,		-- object reference number
  entity      integer DEFAULT 1 NOT NULL,	        -- multi company id
  ref_ext     varchar(255),-- reference into an external system (not used by dolibarr)
  field_one   integer,
  field_two   integer NOT NULL,
  fk_field    integer,
  field_date  datetime,
  datec       timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,,   -- creation datetime
  tms         timestamp,    -- update time stamp
  fk_user_author integer NOT NULL,                     -- Author, foreign key of llx_user
  fk_user_mod    integer NOT NULL,                      -- Last updater, foreign key of llx_user
  import_key	varchar(14)                -- Use by import process
)type=innodb;

示例:用于为表 llx_mytable 创建主键/索引的文件 llx_mytable.key.sql

-- ===========================================================================
-- Copyright (C) 2013 Author <email@author.com>
-- 
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
-- ===========================================================================

ALTER TABLE llx_mytable ADD UNIQUE uk_mytable_field (field_one, field_two);

ALTER TABLE llx_mytable ADD CONSTRAINT fk_mytable_fk_field FOREIGN KEY (fk_field) REFERENCES llx_matablepere (rowid);

表和字段的结构

  • 所有表都有前缀,用以避免与其它项目的命名冲突。目前,前缀可在安装时更改。其默认值为 llx_ 。
  • 表的结构

当您创建一个新表时,建议使用与其他Dolibarr表相同的命名约定。必须要有以下字段:

- rowid INTEGER AUTO_INCREMENT PRIMARY KEY    技术ID
- entity INTEGER default 1                    多公司功能的ID
- date_creation   datetime                    创建日期
- tms             timestamp                   上次修改日期(数据库自行管理,无需通过代码管理)
- import_key                                  如果数据是批量导入的,则保存导入编号YYYYMMDDHHMMSS
- status          smallint                    存储对象的状态

可能字段:

- fk_user_creat integer 创建者的ID(或者是 fk_user_author)
- fk_user_modif integer 修改者的ID
- fk_user_valid integer 确认者/验证者的ID(如果适用)
- fk_soc        integer 合伙方的ID(如果适用)

备注字段:

- note_private text 对象的私有备注
- note_pubic   text 对象的公开备注

或者

- note text 备注(如果不需要区分私有或公开)
  • 字段类型:

在实践中,为了与所有国家/地区对金额要求的任何准确性兼容、与任何数据库语法兼容、以及与Dolibarr升级框架兼容,我们将仅使用以下类型:

- integer		        用于任何整数、ID或外键(bigint 可用于非常大的表ID)
- smallint                      用于任何小尺寸的整数(如存储状态代码)或布尔值
- double(24,8)			用于任何金额
- double(6,3)			用于增值税税率
- real				用于数量
- varchar			用于字符串(包括长度为1的字符串),char类型已被逐渐弃用
- timestamp			用于要自动更新的日期+时间字段
- datetime			用于日期+时间字段
- date				用于日期字段
- text or medium text		用于大字段 (此类字段上不允许有索引)

所有的业务规则必须位于同一个位置,是在PHP代码中,而不是在客户端或数据库中,这就是为什么 enum 类型也不允许使用。

由于兼容性的原因,其他类型是不允许使用的。

主键

表的主键必须是 rowid 。

目前有一些旧表不符合此规则(如 表llx_c_actioncomm 的主键是id),这是历史原因,这种情况不应该再发生。

外键

外键的名称必须以前缀 fk_ 开头,后跟表名(即引用表的名称)(这是必需的,以避免项目中的名称冲突。因为在某些DBMS中,如Postgresql中,即使是不同的表中也不允许名称重复),再后跟字段名(即引用字段的名称)(这是为了允许在同一表中有多个外键)。

示例:fk_facture_fourn_fk_soc 是表 llx_facture_fourn 中的外键,建在字段 fk_soc 上(引用另一个表中的 rowid 字段)

注意:如果您正在开发自己的外部模块,则您的表中不应该有指向 Dolibarr 标准模块表的外键。因为这将破坏 Dolibarr 的升级,修复,备份和还原工具,也可能破坏标准模块的功能。

替代键

有时,我们需要主键以外的其它唯一索引。因此,还可以创建一个替代主键的唯一索引。这样的索引名称以前缀 uk_ 开头,后跟表名(这是必需的,以避免项目中的名称冲突。因为在某些DBMS中,如Postgresql中,即使是不同的表中也不允许名称重复),再后跟描述键的后缀(这是为了允许在同一表中有多个唯一索引)。

示例:uk_societe_code_client 是表 llx_societe 在 code_client 字段上的一个唯一索引

性能索引

某些字段通常用作搜索、排序或连接条件。在这种情况下,应定义性能索引用以提高性能。此类索引将以前缀 idx_ 命名,后跟表名、再后跟索引所在字段的名称。

示例:idx_societe_user_creat 是表 llx_societe 在字段 user_creat 上的性能索引。

SQL编码规则

  • 使用别名/字段命名

在进行 select 时,可以使用别名来简化查询的编写和阅读:

select chp1, chpxxx2 as chp2 from table2 as t1, table2 as t2 where t1.chpx = t2.chpy

但是,不应在 update 请求中使用别名,因为它们与 MySQL 3.1 不兼容。

  • 禁止使用 SELECT * !每个 SELECT 都必须指定要检索的字段的完整列表。这有助于避免混淆。最重要的是,这使代码的重新生成更加容易,并使变更对字段的影响分析成为可能。示例:
SELECT field_a, field_b, field_c FROM table_1 WHERE field_d = '$id'
  • 在 SQL insert 时,必需给字段加引号,但不包括要存储在 double 或 real 类型字段中的金额数字。浮点数字上的引号有时会导致其存储了不同的值。例如,如果字段类型为 double(24,8),则插入412.62时实际上是将值412.61999512(由于隐式的字符串 - 数字转换)存储到数据库中。只有PHP可以看到412.61999512。其他工具将看到412.62,这使其看上去没有问题。但PHP是正确的,数据库中确实存在错误的值。通过删除数字上的引号,就不会出现此问题。

示例:

Good:     INSERT INTO table_1 (field_txt, field_num) VALUES ('txt', 412.62)
Bad:      INSERT INTO table_1 (field_txt, field_num) VALUES ('txt', '412.62')

请注意,浮点数的问题是普遍性的,不仅是在数据库访问上,而且在处理实数时,所有语言都存在浮点数问题。因此,一旦受到影响,就必须使用 price2num 函数清除浮点问题。根据需要,第二个参数设置为:“MU”(如果是单价)、“MT”(如果是总价)或“MS”(其他情况),具体取决于数字的使用情况。另请参阅下面的“实数、金额和计算”一章。

  • SQL命令中不允许使用SQL日期函数NOW、SYSDATE、DATEDIFF。如果可能的话,还必须避免使用MONTH、YEAR。如果必须在字段中使用当前日期,则该值必须来自PHP,例如通过 dol_now() 函数,而不是来自数据库引擎。原因如下:
    • 为了更好的代码可移植性
    • 正确管理TimeZone,并且不依赖于数据库的TimeZone(参考时区是PHP时区,数据库时区可能与此不同,因此日期转换必须在PHP端进行)。
    • 更好的性能(请参阅下面的示例和评论)

示例,不要:

$sql="SELECT rowid FROM table where datefield = NOW()";

要:

$sql="SELECT rowid FROM table where datefield = '".$this->db->idate(dol_now())."'";

示例,不要:

$sql="SELECT rowid FROM table where DATEDIFF(table.datefield, NOW()) > 7";

要:

$sql="SELECT rowid FROM table where datefield < '".$this->db->idate(dol_now() - (7 * 24 * 3600))."'";

此规则的另一个优点是,查询可以从索引使用中获益,因为它将日期字段与固定值进行比较。当使用 datediff 时,因在比较之前对字段进行了处理,使得数据库无法使用该字段的索引。与不使用 datediff 的方案相比,其性能非常差。

  • 禁止使用 WITH ROLLUP

不应使用此语句:不同数据库的处理方式不同。此外,使用 WITH ROLLUP 会破坏返回数据的纯度。通过该指令生成小计的中间聚合可以在PHP的帮助下轻松完成,并有助于保持返回的数据表干净(不会被人工插入的数据损坏)。除了标准化程度不高之外,通过在数据中插入计算结果,给出的结果是数据和聚合业务计算的混合结果,对代码的理解变得复杂,甚至在这些聚合上的代码演变变得复杂时更可能难以理解。

  • 使用 $db->ifsql 替代 IF SQL

不要在SQL查询中使用IF。请改用 $db->ifsql() 方法,您将创建一个与所有SQL数据库兼容的SQL IF。

  • 不使用 DELETE CASCADE 和 UPDATE CASCADE

禁止使用此类SQL语句,因为它们绕过了应用程序的业务规则,给开发人员带来了很多失控的麻烦。例如,如果表A和B之间存在 DELETE CASCADE,当应用程序运行代码删除A中的记录时,表B中的子项也将被删除。如果一个PHP Dolibarr触发器(例如,由外部模块提供)存在于B表记录的删除操作上(例如,验证删除或执行附加操作),则 DELETE CASCADE 将在不执行PHP Dolibarr触发器的情况下仅执行删除B表记录的操作,跳过了由外部模块的PHP Dolibarr触发器执行的验证或附带操作。因此,所有业务规则都必须在同一端(PHP服务器端)实现,这就是为什么不允许在数据库端实现业务规则的原因(与下一节关于数据库触发器的情况相同)。

请注意,外部模块可以将它们(DELETE CASCADE 和 UPDATE CASCADE)用于Dolibarr表及其模块表之间的链接,但最好的推荐解决方案是在删除父表的记录时使用 Dolibarr PHP 触发器来实现其子表记录的删除。

Using Database triggers

Using Database triggers is not allowed into the code of Dolibarr, so you should have no troubles with Database triggers. Database triggers are not portable. Compatibility may be broken when upgrading your version of your database, database triggers are often not included into backup tools, database triggers need permissions that you may not have (and should not have) on a common secured database, database triggers means also that you include some "business rules" of your application into the database where most other rules are managed by the code itself (this can create conflict or code that can't be debugged with a step by step debugger), database triggers execute code using the timezone of the database instead of the reference timezone of application that may be different (generating offset into database) ... There is tons of reason why we do not recommend to use database triggers in your own development. Using Database triggers can save you time when you make development but is a very bad practice, so is forbidden as it is not compatible with the high level of quality of code expected by Dolibarr team. External modules that uses Database triggers may also be refused on the market place since it won't work for more than 50% of users.

Mysql 特点

  • Tables must be declared with format InnoDB.

This format supports foreign keys and their restrictions, and transactions integrity is also supported. This guarantees that Dolibarr events keep all data with correct values between tables even when transaction modify different tables.

  • Dolibarr MUST work even if Mysql option strict is active.

To activate it (required when developing on Dolibarr), add the following line into the config file of your Mysql server (my.cnf or my.ini)

sql-mode="STRICT_ALL_TABLES,ONLY_FULL_GROUP_BY,NO_ZERO_DATE,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

PostgreSQL specificities

Only Mysql SQL files must be maintained. Those files are converted "on the fly" by the database Dolibarr driver.

There is an exception The SQL "UPDATE FROM":

MySQL Syntax:

UPDATE table_taget as target, table_source as source SET fieldtarget=source.fieldsource
WHERE source.rowid=target.rowid;

PgSQL Syntax:

UPDATE table_taget as target SET fieldtarget=source.fieldsource
FROM table_source as source WHERE source.rowid=target.rowid;

There is no native SQL request "update from" in dolibarr core. But in your module you should do :

if ($this->db->type=='pgsql') {
$sql="UPDATE table_taget as target SET fieldtarget=source.fieldsource
FROM table_source as source WHERE source.rowid=target.rowid";
} else {
$sql= "UPDATE table_taget as target, table_source as source SET fieldtarget=source.fieldsource
WHERE source.rowid=target.rowid";
}

HTML 规范

语法规则

  • HTML used must be HTML compliant and not XHTML. All attributes of HTML tags must be in lower case and quoted with ".
  • Links href must be absolute and use the function dol_buildpath() to get absolute path from a relative path and img tag must be build using function img_picto().

For example:

print '<a href="'.dol_buildpath('/mydir/mypage.php').'">'.img_picto('Texte alt','namepictopng','').'</a>';
  • HTML tables must have columns with no forced width, except for columns that contains data we know the length. For example, a column with a picto only can be forced to with="20px".

Otherwise, we must avoid forcing the column width. Reason is that, in most cases, the browser make a better works to define column width automatically than forced values, and it works whatever is the resolution.

  • Javascript/ajax code and call to javascript files into php pages must be avoided. However, if you need to include javascript code, you must add a condition on "$conf->use_javascript_ajax"
if ($conf->use_javascript_ajax) {
...  // php code generating javascript here
}
  • Popup windows must not be used, except for tooltips (and must have a condition as explained before).
  • External scripts must be written in Perl if they can't be written in PHP. Usage of another language is not forbidden but must be argued before in the development mailing-list.

外部模板框架?

There is ton of frameworks to provide a templating language of an HTML page. The best and faster is just called "PHP", and because Dolibarr already depends on PHP, there is no need to introduce a dependency on a third language.

All templating frameworks are just preprocessor, BEFORE PHP. It can't be faster than PHP alone. When we say "speed is increased because templating framework use a cache", you must read in fact "the overtime spent by the framework is reduced by cache, not the speed of processing PHP file". We should say "any templating framework has an overload over PHP, the cache of framework, just reduce the slowing effect of having this framework", but not "the speed is increased, it is always decreased compared to pure PHP".

Above all, having a templating system is completely possible by doing a ".tpl.php" file that dos not contains any logic code, but only HTML and "echo". We get same result (but faster and easier to develop because it does not need to do all the setXXX before calling each template). All variables (known by code that include the template) are automaticaly known into a PHP template page. No risk to forget a set, and a lot of line of codes reduced, a lot of time and development errors are also saved.

Also, keeping a 100% isolation between code and HTML output is interesting in only 1 situation: When teams building design is complety different than team building logic code, AND if you build not too sophisticated pages, AND with no need of too many Ajax features (this need to know how code works). And this situation is surely not the Dolibarr future (team will often be same, Ajax will be more and more present, event if I hope not too much, and screens are more and more dependent of dynamic or contextual events, difficult to have this with onesimple template without transforming the template into a page with high level of code).

There is a ton of other reasons to not use an external templating system and all arguments to use them are also the best argument to use PHP as our templating system.

Dolibarr 规范和代码框架

框架代码

To standardize the code, and to speed up the development of new components in Dolibarr, you'll find 4 skeletons fully prepared in the directory dev/skeletons.

  • 1 that serves as an example of the module description: myModule.class.php
  • 1 that serves as an example of code for creating a new class: skeleton_class.class.php
  • 1 that serves as an example of code for creating a new page: skeleton_page.php
  • 1 that serves as an example of code for creating a script for executing command lines: skeleton_script.php

Use it as an example. Note that the skeletons are also used by the PHP code generator, which is described in the development chapter of Dolibarr modules, to speed up your development.

日期和时区

Dolibarr is an application that is multi-user and multi-location. It's therefore necessary to store dates in the right format. To avoid problems with conversions, the following rules should be applied:

  • A date into memory must always be stored with Timestamp GMT format.
  • A date stored into database, is the GMT Timestamp of date submitted into the request usng the PHP server timezone. This does not apply to date update automatically by database (fields tms into database).

For exemple le 1st january 1970, 3 hour at Paris (TZ=+1) = 2 hour at Greenwitch (TZ=0) will be stored into memory with value 7200 and will be submitted into a SQL request to database with the string '19700101030000' (PHP convert into its TZ hour and database will unconvert it using its timezone too that is same than PHP).

All select methods should translate date fields, that are with format TZ of database ('19700101030000'), into a timestamp field by calling the method db->jdate. This is to store into memory a GTM Timestamp date. All insert methods must convert, during generation of SQL request, the memory date into the string by using db->idate (you may find examples into skeleton).

  • Dates that are updated automatically (field tms into database) contains a GMT Timestamp GMT of date when change is done. The select will also use the db->jdate (that use PHP server TZ) to convert read data into a GMT Timestamp into memory. So if timezone of database differs from timezone of PHP server (one of them is not correctly set), you may experience differences between creation date and update date.
  • Manipulation date with PHP must be done using the Dolibarr date functions: dol_now(), dol_mktime(), dol_stringtotime(), dol_getdate(), dol_time_plus_duree(). You may also find other functions available into file date.lib.php.

UTF8/ISO 编码

Dolibarr stores data in the following way:

  • In database, data is stored in UTF8 or ISO. It depends on the database's pagecode therefore these options are set at creation time. In any case, Dolibarr's database driver (in lib/database) deals with it to convert from/to UTF8 at insertion and readout.
  • Memory data is stored in UTF8 (PHP object instances).
  • Screen displayed web pages are UTF8 (for versions prior to 2.5.1, the deprecated $character_set parameter from conf.php file defines output format).

浮点数,金额和计算

With PHP, like other languages (Java for exemple), non integer data (float, real, double) are not reliable for calculation. Try to make for example

print 239.2 - 229.3 - 9.9;

You wont get zero but a very small decimal number. If you get zero her, you should be able to find other examples that don't work. Problem of float is general, so a variable that is a result of a calculation using decimal numbers must ALWAYS be cleaned using the function price2num() with the econd parameter to: 'MU', 'MT' or 'MS' depending on need (see description of function).

print price2num(239.2 - 229.3 - 9.9, 'MT');

If data manipulated is not an amount, then using MU, MT, MS has no sense, and you must use the function round().

表的创建

Do not create tables, on the fly, during execution by a standard user, we mean, during current usage of software. If you create a module that uses its own table, not available in the default Dolibarr code, then take a look at tutorial Module development. It explains how to provide new tables with your module, so that, the tables will be created during module activation and not during module usage.

比较版本

If your code need to make different things depending on Dolibarr version, you can use the following tip to detect and compare versions

$version=preg_split('/[\.-]/',DOL_VERSION);
if (versioncompare($version,array(5,0,-4)) >= 0) { //mycode for 5.0 only; }	// For dolibarr 5.0.* (the -4 means we include also alpha, beta, rc and rcX)

But this solution need to include the function versioncompare. An alternative solution to test version is to do:

if ((float) DOL_VERSION >= 5.0) { //mycode for 5.0 only; }	// For dolibarr 5.0.*

日志

Add logs to your code using function

dol_syslog($yourmessage, LOG_INFO|LOG_DEBUG|LOG_WARNING|LOG_ERR);

工作目录

If you need to create a working directory, into your code, refer to it with DOL_DATA_ROOT.'/mymodule'

The directory can be created into your code by the following function:

$mymoduledir=DOL_DATA_ROOT.'/mymodule';
dol_mkdir($mymoduledir);

If you need a directory to store temporary data, this directory must be DOL_DATA_ROOT.'/mymodule/temp'

设计模式与对象程序设计

创建设计框 (GoF)

Design patterns defined by the Gang Of Four (see wikipédia on Design patters). No usage of such patterns is required. We found some objects next to Singletons or Factory but not completely compliant with syntax, this is to be compatible with PHP 4 that is not a pure object language.

结构设计模式 (GoF)

Design patterns defined by the Gang Of Four (see wikipédia on Design patters). No usage of such patterns is required.

行为设计模式 (GoF)

Design patterns defined by the Gang Of Four (see wikipédia on Design patters). No usage of such patterns is required.

企业设计模式 (Martin Fowler)

代码组织模式

Martin Fowler has identified 3 ways to organize code:

  • The Transaction Script (The source code is linear for each user action).

This is the old school used by all procedural languages. Inconvenient: Redundancy of code. Need to know the physical model of data to develop.

  • The Domain Model

This notion is available with object languages. It is business process (to identify before) that are used for objects classes. Inconvenient: Model very complex to maintain.

  • The Table Module

This is a mix between 2 previous where we have only one unique class for each table of database.

-> As shown in code skeletons (see previous chapter), Dolibarr uses concept of Table Module.

业务逻辑之间的通信 - data (ORM)

There are 3 ways to make links:

  • The Table And Row Data Gateway

This is the most simple. You have one class per table and each class is a link to the table with CRUD methods (Ceate, Read, Update, Delete). A class instance is a record in the table. The class contains only code to reach lines and fields of table.

Example: This mode is used by some ORM Frameworks, like iBatis.

  • The Active Record

Same as previous, but we are allowed to add some business functions into the class, if such functions are dedicated to the table or recording into this table.

Example: This mode is used for Dolibarr development and most PHP softwares that include their own framework and best practices.

  • The Data Mapper

Classes represent entities of the problem and not the data. So you have to double, triple ... these classes with Mapper classes to access the data. More "purist" on paper (closer of business), this method also has the disadvantage of being more complex in practice.

Example: This is the choice if you use the ORM Framework Propel. We find this model in heavier applications, based on this ORM among others.

-> For Dolibarr development, it is recommended to use the connection mode Active Record, which offers the advantages of a model close to the business without having the complexity, without obfuscating technical architecture. It is by this way that the development, understanding of code and technical maintenance and / or business behaviour seems the more productive (this is however an ongoing debate between the purists and the pragmatists, debate in which nobody can really be right, because it depends on the objectives).