我对 MVC 的使用是否使事情变得过于复杂并导致重复代码?
我已经编写了自己的 PHP MVC,但是我很难区分模型和控制器部分。例如,使用将数据添加到数据库的简单表单,控制器从请求对象中提取表单数据,并将其传递给模型以处理实际的数据库插入。然而,这里似乎有很多重复的代码,完全删除模型部分并简单地让控制器执行数据库插入不是更简单吗?
我知道在某些情况下,我可能有多个控制器使用相同的模型操作,但是有时会发生这种情况,似乎不值得不断分离模型和控制器所需的所有额外编码?
与其说是重复的代码,不如说是一种冗长的做事方式,因为我正在为本质上是一个简单的函数编写大量代码,如果这有意义的话?
控制器的示例代码
// processes the new site data
public function add_new_process() {
// execute action in model
$Model_Websites = new Model_Websites();
$name = $this->request->getPropertyFiltered('sitename',array('sanitize'));
$descrip = $this->request->getPropertyFiltered('descrip',array('sanitize'));
$url = $this->request->getPropertyFiltered('siteurl',array('sanitize'));
$signup_url = $this->request->getPropertyFiltered('signupurl',array('sanitize'));
$acct_id = $this->request->getPropertyFiltered('acct_id',array('sanitize'));
$thumbnail = $this->request->getPropertyFiltered('thumb',array('sanitize'));
if($Model_Websites->addNewSite($name,$descrip,$url,$signup_url,$acct_id,$thumbnail)) {
$this->request->addFeedback("Your new website has been added succesfully!");
$this->request->setFeedbackStatus(true);
$this->request->storeFeedbackInSession();
$this->template->redirectBrowser(__SITE_URL.'/websites/');
} else {
$this->template->setProperty('page_title', Registry::getConfig('site_name').' :: Add New Website' );
$this->template->render('websites','show_form'); // controller,view
}
}
模型的示例代码
function addNewSite($name,$descrip,$url,$signup_url,$acct_id,$thumbnail) {
$pdo = ConnectionFactory::instance()->getConnection();
$stmt = $pdo->prepare("INSERT INTO {$this->db_table_websites} SET
name = :name
, descrip = :descrip
, url = :url
, signup_url = :signup_url
, acct_id = :ccbill_site_id
, thumbnail = :thumbnail
");
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':descrip', $descrip, PDO::PARAM_STR);
$stmt->bindParam(':url', $url, PDO::PARAM_STR);
$stmt->bindParam(':signup_url', $signup_url, PDO::PARAM_STR);
$stmt->bindParam(':acct_id', $acct_id, PDO::PARAM_STR);
$stmt->bindParam(':thumbnail', $thumbnail, PDO::PARAM_STR);
if($stmt->execute()) return true;
else return false;
}
I've wrote my own PHP MVC however i'm struggling to distinguish between the model and controller part. For example with a simple form that will add data to the database, the controller is pulling the form data from a request object, and passing it to the Model to handle the actual database insert. However there seems a lot of somewhat duplicate code in here, would it not be simpler to remove the Model part altogether and simply have the controller do the database insert?
I understand that in some cases i may have multiple controllers using the same Model action, however for the occasioanl time this happens it doesn't seem worth all the extra coding required to constantly seperate the Model and controller?
It's not so much duplicate code more that it seems a long winded way of doing things as i'm writing a lot of code for what is essentially a simple function, if that makes sense?
Sample code from controller
// processes the new site data
public function add_new_process() {
// execute action in model
$Model_Websites = new Model_Websites();
$name = $this->request->getPropertyFiltered('sitename',array('sanitize'));
$descrip = $this->request->getPropertyFiltered('descrip',array('sanitize'));
$url = $this->request->getPropertyFiltered('siteurl',array('sanitize'));
$signup_url = $this->request->getPropertyFiltered('signupurl',array('sanitize'));
$acct_id = $this->request->getPropertyFiltered('acct_id',array('sanitize'));
$thumbnail = $this->request->getPropertyFiltered('thumb',array('sanitize'));
if($Model_Websites->addNewSite($name,$descrip,$url,$signup_url,$acct_id,$thumbnail)) {
$this->request->addFeedback("Your new website has been added succesfully!");
$this->request->setFeedbackStatus(true);
$this->request->storeFeedbackInSession();
$this->template->redirectBrowser(__SITE_URL.'/websites/');
} else {
$this->template->setProperty('page_title', Registry::getConfig('site_name').' :: Add New Website' );
$this->template->render('websites','show_form'); // controller,view
}
}
Sample code from Model
function addNewSite($name,$descrip,$url,$signup_url,$acct_id,$thumbnail) {
$pdo = ConnectionFactory::instance()->getConnection();
$stmt = $pdo->prepare("INSERT INTO {$this->db_table_websites} SET
name = :name
, descrip = :descrip
, url = :url
, signup_url = :signup_url
, acct_id = :ccbill_site_id
, thumbnail = :thumbnail
");
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':descrip', $descrip, PDO::PARAM_STR);
$stmt->bindParam(':url', $url, PDO::PARAM_STR);
$stmt->bindParam(':signup_url', $signup_url, PDO::PARAM_STR);
$stmt->bindParam(':acct_id', $acct_id, PDO::PARAM_STR);
$stmt->bindParam(':thumbnail', $thumbnail, PDO::PARAM_STR);
if($stmt->execute()) return true;
else return false;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,问题是您是否确实想使用 MVC。如果您想使用 MVC,那么您不应该将业务逻辑放入控制器中,因为那不是它应该在的位置。请浏览
但是,没有人强迫您使用 MVC。这是一种常见的模式,当您想要创建可维护的应用程序时,最好使用它。尤其是业务逻辑和表示层的分离更值得考虑。但对于小型应用程序和网站,MVC 可能会过大。您也可以使用一堆事务脚本来构建您的站点,其中每个脚本处理来自 UI 的单个请求。查看
可能的替代方法。
至于你的代码,我不认为它使事情过于复杂。由于代码冗长,它看起来可能就跟原来一样。您可以通过创建 FilterChain (替代)在调用控制器之前透明地清理所有输入。你可以让你的 表单使用分组 这样你就可以传递
$form ['site']
到您的模型,其他值是该模型的子键。此外,您还进行了三个呼叫来设置可能在一次呼叫中处理的反馈。也许您可以编写一个反馈助手来为您执行这三个调用,但这仅公开一种方法并在内部完成剩余的工作(或者使其接受三个参数或减少添加反馈消息所需的工作所需的任何内容) )。Well, the question is whether you do want to use MVC or not. If you want to use MVC, then you should not put business logic into the controller, because that's not where it should be. Please go through
However, no one forces you use MVC. It's a common pattern and it is good practise to use it when you want to create a maintainable application. Especially the separation of business logic and presentation layer make it worth considering. But with small applications and websites, chances are MVC is oversized. You could just as well structure your site with a bunch of Transaction scripts, where each script handles a single request from the UI. Check out
for a possible alternate approach.
As for your code, I dont think it's overcomplicating things. It probably looks just like it was, because of the verbose code. You could streamline it a bit by creating a FilterChain (alternative) that sanitizes all input transparently before your controller is called. And you could make your form use grouping so you can just pass
$form['site']
to your Model with the other values being subkeys of that. Also, you are doing three calls to set the feedback that could probably be handled in one call. Maybe you could write a Feedback Helper to do the three calls for you, but that only exposes one method and does the remaining work internally (or make it accept three arguments or whatever is necessary to cut down on the work needed to add a feedback message).我并不是想无礼,所以请不要错误地理解我的评论...
但是,如果您正在努力解决模型和控制器之间的职责之间的差异,也许 MVC 不是正确的答案您试图解决的问题。 MVC 只是一种模式,并不一定适合所有情况。
但是,回答您的问题...
模型 代表您的应用程序正在处理的对象。订单、客户和发票等都是电子商务应用程序中的模型示例。 MVC 与 Active Record 模式相结合还意味着模型可以持久保存并从数据库中检索自身。
控制员是这个三环马戏团的指挥。控制器有责任与模型对话,并向它们发送适当的消息(如保存、删除等)。
视图负责获取控制器已获取、创建等的数据(即模型)并显示它们。该视图可以呈现为 HTML、JSON 或其他任何内容。
而且,作为结束语...是否还没有为 PHP 编写的 MVC 框架?
I am not trying to be rude, so please don't take my comments incorrectly...
However, if you are struggling with the difference between what the responsibilities are between the model and the controller, perhaps MVC isn't the right answer for the problems you are trying to solve. MVC is just a pattern, and it isn't necessarily right in every situation.
But, in answer to your question...
The Model represents the objects your application is dealing with. Things like an Order, Customer, and Invoice are examples of models in an e-commerce application. MVC coupled with an Active Record pattern also implies that the models persist and retrieve themselves from the database.
The Controller is the conductor of this three ring circus. It is the controller's responsibility to talk to the models, and send them appropriate messages (like save, delete, etc).
The View is responsable for taking data (i.e., Models) that the Controller has fetched, created, etc and displaying them. The view can render to HTML, JSON, or anything else.
And, as a closing comment... are there not already MVC frameworks written for PHP?
您的控制器执行视图和模型之间的所有数据操作。这可能是根据需要解析数据、数学运算等。该模型仅保存/更新/删除记录。所以不要删除控制器或模型。只是尽量不要混合各层之间的任务。
Your Controller do all data manipulations between the View and the Model. This could be parsing data, maths manipulations and so on as required. The model just saves/update/delete records. So no don't remove neither Controller or Model. Just try not to mix the tasks between layers.