我有一堆功能,我想进入一个类.它们目前被分成几个相当长的文件.我不希望有一个2500行文件,但据我所知,你不能使用include将一个类拆分成多个文件.从理论上讲,我可以将函数分组到不同的类中,但它们之间的关系非常密切,我觉得它们属于一体,并且将它们分开会减少我希望从程序方法中脱离出来的一些实用工具. (使用共享属性,而不是几乎每个函数中的一堆参数).
我知道这有点模糊,但任何建议/指针?如果重要,那就是原型,因此代码管理的简易性优先于安全性和性能.
更新:让我看看我是否可以删除一些模糊性:
此类/函数集输出复杂形式的html.每个部分中有许多不同的部分和变体,取决于当前传递到函数中的约5或6个参数.我希望将参数定义为类的属性,然后从所有节创建方法中访问它们.如果我使用子类,那些属性的值将不会被正确初始化,因此需要一个类. (嗯……除非我把它们定义为静态.我可能刚刚回答了我自己的问题.我将不得不查看是否有任何理由不起作用.)
我目前有很多功能,如:
- get_section_A ($type='foo',$mode='bar',$read_only=false,$values_array=array()) {
- if ($this->type == 'foo') { }
- else ($this->type == 'foo') { }
- }
所以我最初想象的是:
- class MyForm {
- public $type; // or maybe they'd be private or
- public $mode; // I'd use getters and setters
- public $read_only; // let's not get distracted by that :)
- public $values_array;
- // etc.
- function __constructor ($type='foo',$values_array=array()) {
- $this->type = $type;
- // etc.
- }
- function get_sections () {
- $result = $this->get_section_A();
- $result .= $this->get_section_B();
- $result .= $this->get_section_C();
- }
- function get_section_A() {
- if ($this->type == 'foo') { }
- else { }
- }
- function get_section_B() {}
- function get_section_C() {}
- // etc. for 2500 lines
- }
现在我想的是:
- // container class file
- class MyForm {
- static $type
- static $mode
- static $read_only
- static $values_array
- // etc.
- function __constructor ($type='foo',$values_array=array()) {
- MyForm::$type = $type;
- // etc.
- }
- function get_sections () {
- $result = new SectionA();
- $result .= new SectionB();
- $result .= new SectionC();
- }
- }
- // section A file
- class SectionA extends MyForm {
- function __constructor() {
- if (MyForm::$type == 'foo') { }
- else { }
- }
- function __toString() {
- // return string representation of section
- }
- }
- // etc.
或者我可能需要一个FormSection的抽象类,其中属性存在.
还有其他想法/方法吗?
我将它们分成你想要的任意数量的课程(或许多有意义的课程),然后将其分成
define an autoloader以消除包容性问题.
编辑
好的,看到更多的代码后 – 我认为你正在接近子类错误.你有很多针对$type的if语句,它告诉我这是多态应该基于的.
- abstract class MyForm
- {
- protected
- $mode,$read_only,$values
- ;
- public function __construct( $mode,array $values = array() )
- {
- $this->mode = $mode;
- $this->read_only = (boolean)$read_only;
- $this->values = $values;
- }
- abstract function get_section_A();
- abstract function get_section_B();
- abstract function get_section_C();
- // final only if you don't want subclasses to override
- final public function get_sections()
- {
- return $this->get_section_A()
- . $this->get_section_B()
- . $this->get_section_C()
- ;
- }
- }
- class FooForm extends MyForm
- {
- public function get_section_A()
- {
- // whatever
- }
- public function get_section_B()
- {
- // whatever
- }
- public function get_section_C()
- {
- // whatever
- }
- }