Schema.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: leo
  5. * Date: 2018/3/23
  6. * Time: 上午9:16
  7. */
  8. namespace common\helpers;
  9. use yii\db\TableSchema;
  10. class Schema extends \yii\db\oci\Schema
  11. {
  12. /**
  13. * 重写载入表结构方法
  14. * @param string $name
  15. * @return mixed|null|TableSchema
  16. */
  17. protected function loadTableSchema($name)
  18. {
  19. $dbName = strtoupper($this->db->username);
  20. if(strpos($name, $dbName) === 0){
  21. $tableName = $name;
  22. } else {
  23. $tableName = $dbName.'.'.$name;
  24. }
  25. $path = \Yii::getAlias('@common/runtime/tableSchema/').$tableName;
  26. $table = null;
  27. if(file_exists($path)){
  28. $cache = file_get_contents($path);
  29. $table = unserialize($cache);
  30. }
  31. if(!$table){
  32. $oriEnableSlaves = $this->db->enableSlaves;
  33. $this->db->enableSlaves = false;
  34. $table = new TableSchema();
  35. $this->resolveTableNames($table, $name);
  36. if ($this->findColumns($table)) {
  37. $this->findConstraints($table);
  38. $cacheContent = serialize($table);
  39. file_put_contents($path, $cacheContent);
  40. $this->db->enableSlaves = $oriEnableSlaves;
  41. return $table;
  42. }
  43. $this->db->enableSlaves = $oriEnableSlaves;
  44. return null;
  45. }
  46. return $table;
  47. }
  48. /**
  49. * 对外公共的方法生成表缓存
  50. * @param $name
  51. */
  52. public function generateTableSchema($name){
  53. $this->loadTableSchema($name);
  54. }
  55. /**
  56. * 清空表结构缓存
  57. */
  58. public function clearTableSchemaCache(){
  59. $path = \Yii::getAlias('@common/runtime/tableSchema/');
  60. $waitDel = scandir($path);
  61. foreach($waitDel as $file){
  62. if($file === '.gitignore') continue;
  63. unlink($path.$file);
  64. }
  65. }
  66. }