⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 model.php

📁 Cake Framwork , Excellent
💻 PHP
📖 第 1 页 / 共 3 页
字号:
					$out .= "\n";				}				$out .= "\t);\n\n";			}			if (!empty($associations['hasAndBelongsToMany'])) {				$out .= "\tvar \$hasAndBelongsToMany = array(\n";				$hasAndBelongsToManyCount = count($associations['hasAndBelongsToMany']);				for ($i = 0; $i < $hasAndBelongsToManyCount; $i++) {					$out .= "\t\t\t'{$associations['hasAndBelongsToMany'][$i]['alias']}' => ";					$out .= "array('className' => '{$associations['hasAndBelongsToMany'][$i]['className']}',\n";					$out .= "\t\t\t\t\t\t'joinTable' => '{$associations['hasAndBelongsToMany'][$i]['joinTable']}',\n";					$out .= "\t\t\t\t\t\t'foreignKey' => '{$associations['hasAndBelongsToMany'][$i]['foreignKey']}',\n";					$out .= "\t\t\t\t\t\t'associationForeignKey' => '{$associations['hasAndBelongsToMany'][$i]['associationForeignKey']}',\n";					$out .= "\t\t\t\t\t\t'unique' => true,\n";					$out .= "\t\t\t\t\t\t'conditions' => '',\n";					$out .= "\t\t\t\t\t\t'fields' => '',\n";					$out .= "\t\t\t\t\t\t'order' => '',\n";					$out .= "\t\t\t\t\t\t'limit' => '',\n";					$out .= "\t\t\t\t\t\t'offset' => '',\n";					$out .= "\t\t\t\t\t\t'finderQuery' => '',\n";					$out .= "\t\t\t\t\t\t'deleteQuery' => '',\n";					$out .= "\t\t\t\t\t\t'insertQuery' => ''\n";					$out .= "\t\t\t)";					if ($i + 1 < $hasAndBelongsToManyCount) {						$out .= ",";					}					$out .= "\n";				}				$out .= "\t);\n\n";			}		}		$out .= "}\n";		$out .= "?>";		$filename = $this->path . Inflector::underscore($name) . '.php';		$this->out("\nBaking model class for $name...");		return $this->createFile($filename, $out);	}/** * Assembles and writes a unit test file * * @param string $className Model class name * @access private */	function bakeTest($className, $useTable = null, $associations = array()) {		$results = $this->fixture($className, $useTable);		if ($results) {			$fixtureInc = 'app';			if ($this->plugin) {				$fixtureInc = 'plugin.'.Inflector::underscore($this->plugin);			}			$fixture[] = "'{$fixtureInc}." . Inflector::underscore($className) ."'";			if (!empty($associations)) {				$assoc[] = Set::extract($associations, 'belongsTo.{n}.className');				$assoc[] = Set::extract($associations, 'hasOne.{n}.className');				$assoc[] = Set::extract($associations, 'hasMany.{n}.className');				foreach ($assoc as $key => $value) {					if (is_array($value)) {						foreach ($value as $class) {							$fixture[] = "'{$fixtureInc}." . Inflector::underscore($class) ."'";						}					}				}			}			$fixture = join(", ", $fixture);			$import = $className;			if (isset($this->plugin)) {				$import = $this->plugin . '.' . $className;			}			$out = "App::import('Model', '$import');\n\n";			$out .= "class Test{$className} extends {$className} {\n";			$out .= "\tvar \$cacheSources = false;\n";			$out .= "\tvar \$useDbConfig  = 'test_suite';\n}\n\n";			$out .= "class {$className}TestCase extends CakeTestCase {\n";			$out .= "\tvar \${$className} = null;\n";			$out .= "\tvar \$fixtures = array($fixture);\n\n";			$out .= "\tfunction start() {\n\t\tparent::start();\n\t\t\$this->{$className} = new Test{$className}();\n\t}\n\n";			$out .= "\tfunction test{$className}Instance() {\n";			$out .= "\t\t\$this->assertTrue(is_a(\$this->{$className}, '{$className}'));\n\t}\n\n";			$out .= "\tfunction test{$className}Find() {\n";			$out .= "\t\t\$results = \$this->{$className}->recursive = -1;\n";			$out .= "\t\t\$results = \$this->{$className}->find('first');\n\t\t\$this->assertTrue(!empty(\$results));\n\n";			$out .= "\t\t\$expected = array('$className' => array(\n$results\n\t\t\t));\n";			$out .= "\t\t\$this->assertEqual(\$results, \$expected);\n\t}\n}\n";			$path = MODEL_TESTS;			if (isset($this->plugin)) {				$pluginPath = 'plugins' . DS . Inflector::underscore($this->plugin) . DS;				$path = APP . $pluginPath . 'tests' . DS . 'cases' . DS . 'models' . DS;			}			$filename = Inflector::underscore($className).'.test.php';			$this->out("\nBaking unit test for $className...");			$header = '$Id';			$content = "<?php \n/* SVN FILE: $header$ */\n/* ". $className ." Test cases generated on: " . date('Y-m-d H:m:s') . " : ". time() . "*/\n{$out}?>";			return $this->createFile($path . $filename, $content);		}		return false;	}/** * outputs the a list of possible models or controllers from database * * @param string $useDbConfig Database configuration name * @access public */	function listAll($useDbConfig = 'default', $interactive = true) {		$db =& ConnectionManager::getDataSource($useDbConfig);		$usePrefix = empty($db->config['prefix']) ? '' : $db->config['prefix'];		if ($usePrefix) {			$tables = array();			foreach ($db->listSources() as $table) {				if (!strncmp($table, $usePrefix, strlen($usePrefix))) {					$tables[] = substr($table, strlen($usePrefix));				}			}		} else {			$tables = $db->listSources();		}		if (empty($tables)) {			$this->err(__('Your database does not have any tables.', true));			$this->_stop();		}		$this->__tables = $tables;		if ($interactive === true) {			$this->out(__('Possible Models based on your current database:', true));			$this->_modelNames = array();			$count = count($tables);			for ($i = 0; $i < $count; $i++) {				$this->_modelNames[] = $this->_modelName($tables[$i]);				$this->out($i + 1 . ". " . $this->_modelNames[$i]);			}		}	}/** * Forces the user to specify the model he wants to bake, and returns the selected model name. * * @return string the model name * @access public */	function getName($useDbConfig) {		$this->listAll($useDbConfig);		$enteredModel = '';		while ($enteredModel == '') {			$enteredModel = $this->in(__("Enter a number from the list above, type in the name of another model, or 'q' to exit", true), null, 'q');			if ($enteredModel === 'q') {				$this->out(__("Exit", true));				$this->_stop();			}			if ($enteredModel == '' || intval($enteredModel) > count($this->_modelNames)) {				$this->err(__("The model name you supplied was empty, or the number you selected was not an option. Please try again.", true));				$enteredModel = '';			}		}		if (intval($enteredModel) > 0 && intval($enteredModel) <= count($this->_modelNames)) {			$currentModelName = $this->_modelNames[intval($enteredModel) - 1];		} else {			$currentModelName = $enteredModel;		}		return $currentModelName;	}/** * Displays help contents * * @access public */	function help() {		$this->hr();		$this->out("Usage: cake bake model <arg1>");		$this->hr();		$this->out('Commands:');		$this->out("\n\tmodel\n\t\tbakes model in interactive mode.");		$this->out("\n\tmodel <name>\n\t\tbakes model file with no associations or validation");		$this->out("");		$this->_stop();	}/** * Builds the tests fixtures for the model and create the file * * @param string $model the name of the model * @param string $useTable table name * @return array $records, used in ModelTask::bakeTest() to create $expected * @todo move this to a task */	function fixture($model, $useTable = null) {		if (!class_exists('CakeSchema')) {			App::import('Model', 'Schema');		}		$out = "\nclass {$model}Fixture extends CakeTestFixture {\n";		$out .= "\tvar \$name = '$model';\n";		if (!$useTable) {			$useTable = Inflector::tableize($model);		} else {			$out .= "\tvar \$table = '$useTable';\n";		}		$schema = new CakeSchema();		$data = $schema->read(array('models' => false));		if (!isset($data['tables'][$useTable])) {			return false;		}		$tables[$model] = $data['tables'][$useTable];		foreach ($tables as $table => $fields) {			if (!is_numeric($table) && $table !== 'missing') {				$out .= "\tvar \$fields = array(\n";				$records = array();				if (is_array($fields)) {					$cols = array();					foreach ($fields as $field => $value) {						if ($field != 'indexes') {							if (is_string($value)) {								$type = $value;								$value = array('type'=> $type);							}							$col = "\t\t\t'{$field}' => array('type'=>'" . $value['type'] . "', ";							switch ($value['type']) {								case 'integer':									$insert = 1;								break;								case 'string';									$insert = "Lorem ipsum dolor sit amet";									if (!empty($value['length'])) {										$insert = substr($insert, 0, (int)$value['length'] - 2);									}									$insert = "'$insert'";								break;								case 'datetime':									$ts = date('Y-m-d H:i:s');									$insert = "'$ts'";								break;								case 'date':									$ts = date('Y-m-d');									$insert = "'$ts'";								break;								case 'time':									$ts = date('H:i:s');									$insert = "'$ts'";								break;								case 'boolean':									$insert = 1;								break;								case 'text':									$insert =									'\'Lorem ipsum dolor sit amet, aliquet feugiat. Convallis morbi fringilla gravida,									phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin venenatis cum nullam,									vivamus ut a sed, mollitia lectus. Nulla vestibulum massa neque ut et, id hendrerit sit,									feugiat in taciti enim proin nibh, tempor dignissim, rhoncus duis vestibulum nunc mattis convallis.									Orci aliquet, in lorem et velit maecenas luctus, wisi nulla at, mauris nam ut a, lorem et et elit eu.									Sed dui facilisi, adipiscing mollis lacus congue integer, faucibus consectetuer eros amet sit sit,									magna dolor posuere. Placeat et, ac occaecat rutrum ante ut fusce. Sit velit sit porttitor non enim purus,									id semper consectetuer justo enim, nulla etiam quis justo condimentum vel, malesuada ligula arcu. Nisl neque,									ligula cras suscipit nunc eget, et tellus in varius urna odio est. Fuga urna dis metus euismod laoreet orci,									litora luctus suspendisse sed id luctus ut. Pede volutpat quam vitae, ut ornare wisi. Velit dis tincidunt,									pede vel eleifend nec curabitur dui pellentesque, volutpat taciti aliquet vivamus viverra, eget tellus ut									feugiat lacinia mauris sed, lacinia et felis.\'';								break;							}							$records[] = "\t\t\t'$field'  => $insert";							unset($value['type']);							$col .= join(', ',  $schema->__values($value));						} else {							$col = "\t\t\t'indexes' => array(";							$props = array();							foreach ((array)$value as $key => $index) {								$props[] = "'{$key}' => array(".join(', ',  $schema->__values($index)).")";							}							$col .= join(', ', $props);						}						$col .= ")";						$cols[] = $col;					}					$out .= join(",\n", $cols);				}				$out .= "\n\t\t\t);\n";			}		}		$records = join(",\n", $records);		$out .= "\tvar \$records = array(array(\n$records\n\t\t\t));\n";		$out .= "}\n";		$path = TESTS . DS . 'fixtures' . DS;		if (isset($this->plugin)) {			$pluginPath = 'plugins' . DS . Inflector::underscore($this->plugin) . DS;			$path = APP . $pluginPath . 'tests' . DS . 'fixtures' . DS;		}		$filename = Inflector::underscore($model).'_fixture.php';		$header = '$Id';		$content = "<?php \n/* SVN FILE: $header$ */\n/* ". $model ." Fixture generated on: " . date('Y-m-d H:m:s') . " : ". time() . "*/\n{$out}?>";		$this->out("\nBaking test fixture for $model...");		if ($this->createFile($path . $filename, $content)) {			return $records;		}		return false;	}}?>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -