摘录自 Robert C. Martin的Clean Code 书中的软件工程师的原则 ,适用于php。 这不是风格指南。 这是一个关于开发可读、可复用并且可重构的PHP软件指南。 并不是这里所有的原则都得遵循,甚至很少的能被普遍接受。 这些虽然只是指导,但是都是Clean Code作者多年总结出来的。
Bad:
$ymdstr = $moment->format(‘y-m-d‘);
Good:
$currentDate = $moment->format(‘y-m-d‘);
Bad:
getUserInfo();
getClientData();
getCustomerRecord();
Good:
getUser();
Bad:
// What the heck is 86400 for?
addExpireAt(86400);
Good:
// Declare them as capitalized `const` globals.
interface DateGlobal {
  const SECONDS_IN_A_DAY = 86400;
}
 
addExpireAt(DateGlobal::SECONDS_IN_A_DAY);
Bad:
$address = ‘One Infinite Loop, Cupertino 95014‘;
$cityZipCodeRegex = ‘/^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/‘;
preg_match($cityZipCodeRegex, $address, $matches);
saveCityZipCode($matches[1], $matches[2]);
Good:
$address = ‘One Infinite Loop, Cupertino 95014‘;
$cityZipCodeRegex = ‘/^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/‘;
preg_match($cityZipCodeRegex, $address, $matches);
list(, $city, $zipCode) = $matchers;
saveCityZipCode($city, $zipCode);
Bad:
$l = [‘Austin‘, ‘New York‘, ‘San Francisco‘];
foreach($i=0; $i<count($l); $i++) {
  oStuff();
  doSomeOtherStuff();
  // ...
  // ...
  // ...
  // 等等`$l` 又代表什么?
  dispatch($l);
}
Good:
$locations = [‘Austin‘, ‘New York‘, ‘San Francisco‘];
foreach($i=0; $i<count($locations); $i++) {
  $location = $locations[$i];
 
  doStuff();
  doSomeOtherStuff();
  // ...
  // ...
  // ...
  dispatch($location);
});
Bad:
$car = [
  ‘carMake‘  => ‘Honda‘,
  ‘carModel‘ => ‘Accord‘,
  ‘carColor‘ => ‘Blue‘,
];
 
function paintCar(&$car) {
  $car[‘carColor‘] = ‘Red‘;
}
Good:
$car = [
  ‘make‘  => ‘Honda‘,
  ‘model‘ => ‘Accord‘,
  ‘color‘ => ‘Blue‘,
];
 
function paintCar(&$car) {
  $car[‘color‘] = ‘Red‘;
}
Bad:
function createMicrobrewery($name = null) {
  $breweryName = $name ?: ‘Hipster Brew Co.‘;
  // ...
}
Good:
function createMicrobrewery($breweryName = ‘Hipster Brew Co.‘) {
  // ...
}
Bad:
function createMenu($title, $body, $buttonText, $cancellable) {
  // ...
}
Good:
class menuConfig() {
  public $title;
  public $body;
  public $buttonText;
  public $cancellable = false;
}
 
$config = new MenuConfig();
$config->title = ‘Foo‘;
$config->body = ‘Bar‘;
$config->buttonText = ‘Baz‘;
$config->cancellable = true;
 
function createMenu(MenuConfig $config) {
  // ...
}
Bad:
function emailClients($clients) {
  foreach ($clients as $client) {
    $clientRecord = $db->find($client);
    if($clientRecord->isActive()) {
       email($client);
    }
  }
}
Good:
function emailClients($clients) {
  $activeClients = activeClients($clients);
  array_walk($activeClients, ‘email‘);
}
 
function activeClients($clients) {
  return array_filter($clients, ‘isClientActive‘);
}
 
function isClientActive($client) {
  $clientRecord = $db->find($client);
  return $clientRecord->isActive();
}
Bad:
function addToDate($date, $month) {
  // ...
}
 
$date = new \DateTime();
 
// It‘s hard to to tell from the function name what is added
addToDate($date, 1);
Good:
function addMonthToDate($month, $date) {
  // ...
}
 
$date = new \DateTime();
addMonthToDate(1, $date);
Bad:
function parseBetterJSAlternative($code) {
  $regexes = [
    // ...
  ];
 
  $statements = split(‘ ‘, $code);
  $tokens = [];
  foreach($regexes as $regex) {
    foreach($statements as $statement) {
      // ...
    }
  }
 
  $ast = [];
  foreach($tokens as $token) {
     // lex...
  }
 
  foreach($ast as $node) {
   // parse...
  }
}
Good:
function tokenize($code) {
  $regexes = [
    // ...
  ];
 
  $statements = split(‘ ‘, $code);
  $tokens = [];
  foreach($regexes as $regex) {
    foreach($statements as $statement) {
      $tokens[] = /* ... */;
    });
  });
 
  return tokens;
}
 
function lexer($tokens) {
  $ast = [];
  foreach($tokens as $token) {
    $ast[] = /* ... */;
  });
 
  return ast;
}
 
function parseBetterJSAlternative($code) {
  $tokens = tokenize($code);
  $ast = lexer($tokens);
  foreach($ast as $node) {
    // parse...
  });
}
Bad:
function showDeveloperList($developers) {
  foreach($developers as $developer) {
    $expectedSalary = $developer->calculateExpectedSalary();
    $experience = $developer->getExperience();
    $githubLink = $developer->getGithubLink();
    $data = [
      $expectedSalary,
      $experience,
      $githubLink
    ];
 
    render($data);
  }
}
 
function showManagerList($managers) {
  foreach($managers as $manager) {
    $expectedSalary = $manager->calculateExpectedSalary();
    $experience = $manager->getExperience();
    $githubLink = $manager->getGithubLink();
    $data = [
      $expectedSalary,
      $experience,
      $githubLink
    ];
 
    render($data);
  }
}
Good:
function showList($employees) {
  foreach($employees as $employe) {
    $expectedSalary = $employe->calculateExpectedSalary();
    $experience = $employe->getExperience();
    $githubLink = $employe->getGithubLink();
    $data = [
      $expectedSalary,
      $experience,
      $githubLink
    ];
 
    render($data);
  }
}
Bad:
$menuConfig = [
  ‘title‘       => null,
  ‘body‘        => ‘Bar‘,
  ‘buttonText‘  => null,
  ‘cancellable‘ => true,
];
 
function createMenu(&$config) {
  $config[‘title‘]       = $config[‘title‘] ?: ‘Foo‘;
  $config[‘body‘]        = $config[‘body‘] ?: ‘Bar‘;
  $config[‘buttonText‘]  = $config[‘buttonText‘] ?: ‘Baz‘;
  $config[‘cancellable‘] = $config[‘cancellable‘] ?: true;
}
 
createMenu($menuConfig);
Good:
$menuConfig = [
  ‘title‘       => ‘Order‘,
  // User did not include ‘body‘ key
  ‘buttonText‘  => ‘Send‘,
  ‘cancellable‘ => true,
];
 
function createMenu(&$config) {
  $config = array_merge([
    ‘title‘       => ‘Foo‘,
    ‘body‘        => ‘Bar‘,
    ‘buttonText‘  => ‘Baz‘,
    ‘cancellable‘ => true,
  ], $config);
 
  // config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true}
  // ...
}
 
createMenu($menuConfig);
Bad:
function createFile(name, temp = false) {
  if (temp) {
    touch(‘./temp/‘.$name);
  } else {
    touch($name);
  }
}
Good:
function createFile($name) {
  touch(name);
}
 
function createTempFile($name) {
  touch(‘./temp/‘.$name);
}
Bad:
// Global variable referenced by following function.
// If we had another function that used this name, now it‘d be an array and it could break it.
$name = ‘Ryan McDermott‘;
 
function splitIntoFirstAndLastName() {
  $name = preg_split(‘/ /‘, $name);
}
 
splitIntoFirstAndLastName();
 
var_dump($name); // [‘Ryan‘, ‘McDermott‘];
Good:
$name = ‘Ryan McDermott‘;
 
function splitIntoFirstAndLastName($name) {
  return preg_split(‘/ /‘, $name);
}
 
$name = ‘Ryan McDermott‘;
$newName = splitIntoFirstAndLastName(name);
 
var_export($name); // ‘Ryan McDermott‘;
var_export($newName); // [‘Ryan‘, ‘McDermott‘];
Bad:
function config() {
  return  [
    ‘foo‘: ‘bar‘,
  ]
};
Good:
class Configuration {
  private static $instance;
  private function __construct($configuration) {/* */}
  public static function getInstance() {
     if(self::$instance === null) {
         self::$instance = new Configuration();
     }
     return self::$instance;
 }
 public function get($key) {/* */}
 public function getAll() {/* */}
}
 
$singleton = Configuration::getInstance();
Bad:
if ($fsm->state === ‘fetching‘ && is_empty($listNode)) {
  // ...
}
Good:
function shouldShowSpinner($fsm, $listNode) {
  return $fsm->state === ‘fetching‘ && is_empty(listNode);
}
 
if (shouldShowSpinner($fsmInstance, $listNodeInstance)) {
  // ...
}
Bad:
function isdomNodeNotPresent($node) {
  // ...
}
 
if (!isDOMNodeNotPresent($node)) {
  // ...
}
Good:
function isDOMNodePresent($node) {
  // ...
}
 
if (isDOMNodePresent($node)) {
  // ...
}
Bad:
class Airplane {
  // ...
  public function getCruisingAltitude() {
    switch (this.type) {
      case ‘777‘:
        return $this->getMaxAltitude() - $this->getPassengerCount();
      case ‘Air Force One‘:
        return $this->getMaxAltitude();
      case ‘Cessna‘:
        return $this->getMaxAltitude() - $this->getFuelExpenditure();
    }
  }
}
Good:
class Airplane {
  // ...
}
 
class Boeing777 extends Airplane {
  // ...
  public function getCruisingAltitude() {
    return $this->getMaxAltitude() - $this->getPassengerCount();
  }
}
 
class AirForceOne extends Airplane {
  // ...
  public function getCruisingAltitude() {
    return $this->getMaxAltitude();
  }
}
 
class Cessna extends Airplane {
  // ...
  public function getCruisingAltitude() {
    return $this->getMaxAltitude() - $this->getFuelExpenditure();
  }
}
Bad:
function travelToTexas($vehicle) {
  if ($vehicle instanceof Bicycle) {
    $vehicle->peddle($this->currentLocation, new Location(‘texas‘));
  } else if ($vehicle instanceof Car) {
    $vehicle->drive($this->currentLocation, new Location(‘texas‘));
  }
}
Good:
function travelToTexas($vehicle) {
  $vehicle->move($this->currentLocation, new Location(‘texas‘));
}
Bad:
function combine($val1, $val2) {
  if (is_numeric($val1) && is_numeric(val2)) {
    return val1 + val2;
  }
 
  throw new \Exception(‘Must be of type Number‘);
}
Good:
function combine(int $val1, int $val2) {
  return $val1 + $val2;
}
Bad:
function oldRequestModule($url) {
  // ...
}
 
function newRequestModule($url) {
  // ...
}
 
$req = new newRequestModule();
inventoryTracker(‘apples‘, $req, ‘www.inventory-awesome.io‘);
Good:
function newRequestModule($url) {
  // ...
}
 
$req = new newRequestModule();
inventoryTracker(‘apples‘, $req, ‘www.inventory-awesome.io‘);本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!
 
 PHP 一直受到全球 Web开发人员的青睐,它为人们提供了创建高度交互性和直观的网站和Web应用程序的良好方式,包括语言的广度、深度,且执行简单。以下五个原因,我们来说明PHP是世界 Web开发的最佳语言
 
 PHP中使用OpenSSL生成RSA公钥私钥及进行加密解密示例(非对称加密),php服务端与客户端交互、提供开放api时,通常需要对敏感的部分api数据传输进行数据加密,这时候rsa非对称加密就能派上用处了,下面通过一个例子来说明如何用php来实现数据的加密解密
 
 PHP7中不要做的 10 件事: 不要使用 mysql_ 函数、不要编写垃圾代码、不要在文件末尾使用 PHP 闭合标签、 不要做不必要的引用传递、不要在循环中执行查询、不要在 SQL 查询中使用 *
PHP如何打造一个高可用高性能的网站呢?我们来分析分析高性能高可用的系统。简而言之,采用分布式系统,分布式应用和服务,分布式数据和存储,分布式静态资源,分布式计算,分布式配置和分布式锁。负载均衡,故障转移,实现高并发。
 
 在PHP获取客户端IP时,常使用REMOTE_ADDR,但如果客户端是使用代理服务器来访问,那取到的是代理服务器的 IP 地址,而不是真正的客户端 IP 地址。要想透过代理服务器取得客户端的真实 IP 地址,就要使用HTTP_X_FORWARDED_FOR
 
 首先需要解释的是什么是守护进程。守护进程就是在后台一直运行的进程。比如我们启动的httpd,mysqld等进程都是常驻内存内运行的程序。
后台上传png图片透明底变成黑色的问题,php缩放gif和png图透明背景变成黑色的解决方法,本文讲的是php缩放gif和png图透明背景变成黑色的解决方法, 工作中需要缩放一些gif图然后在去Imagecopymerge
PHP超级全局变量(9个),$GLOBALS 储存全局作用域中的变量,$_SERVER 获取服务器相关信息;PHP魔术变量(8个)__LINE__文件中的当前行号。__FILE__文件的完整路径和文件名。如果用在被包含文件中,则返回被包含的文件名。PHP魔术函数(13个)
如果能将类的方法定义成static,就尽量定义成static,它的速度会提升将近4倍。echo 比 print 快,并且使用echo的多重参数(译注:指用逗号而不是句点)代替字符串连接,比如echo $str1,$str2。
业务中有一块采用了PHP的pcntl_fork多进程,希望能提高效率,但是在执行的时候数据库报错,MySQL能有的连接数量。当主要MySQL线程在一个很短时间内得到非常多的连接请求,这就起作用,然后主线程花些时间(尽管很短)检查连接并且启动一个新线程。
内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!