关于OpenCart的一个小建议

OpenCart是一套老牌的开源自由B2C电商系统,最近watch了其托管在在github上的项目,发现还是很活跃的,每天都有人反馈bug。

初步的看一下,它是支持在后台管理多个店铺的,而且可以同一个商品在不同店铺有不同的价格;店铺之间可以绑定不同的域名。这是一个比较有特色的地方。

但查看它的代码,就发现多年来改动很小,在代码的分工上,没有进化的感觉。

大量本该由视图来进行构造的数据如语言、链接、当前路径等,都放到控制器中,

像前台登录页面:

$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/home')
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_account'),
			'href' => $this->url->link('account/account', '', 'SSL')
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_login'),
			'href' => $this->url->link('account/login', '', 'SSL')
		);

		$data['heading_title'] = $this->language->get('heading_title');

		$data['text_new_customer'] = $this->language->get('text_new_customer');
		$data['text_register'] = $this->language->get('text_register');
		$data['text_register_account'] = $this->language->get('text_register_account');
		$data['text_returning_customer'] = $this->language->get('text_returning_customer');
		$data['text_i_am_returning_customer'] = $this->language->get('text_i_am_returning_customer');
		$data['text_forgotten'] = $this->language->get('text_forgotten');

		$data['entry_email'] = $this->language->get('entry_email');
		$data['entry_password'] = $this->language->get('entry_password');

		$data['button_continue'] = $this->language->get('button_continue');
		$data['button_login'] = $this->language->get('button_login');

		if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}

		$data['action'] = $this->url->link('account/login', '', 'SSL');
		$data['register'] = $this->url->link('account/register', '', 'SSL');
		$data['forgotten'] = $this->url->link('account/forgotten', '', 'SSL');

相当累赘,其实在现有框架特性下,完全可以放到视图文件中去的。

在视图文件的头部:

<?php

$lang = $this->registry->get('language');//加载语言包管理对象
$url = $this->registry->get('url');//加载url对象

$this->language('common/footer');//载入语言包

?>
<footer>
  <div class="container">
    <div class="row">
      <?php if ($informations) { ?>
      <div class="col-sm-3">
        <h5><?php echo $lang->get('text_information'); ?></h5>
        <ul class="list-unstyled">
          <?php foreach ($informations as $information) { ?>
          <li><a href="<?php echo $information['href']; ?>"><?php echo $information['title']; ?></a></li>
          <?php } ?>
        </ul>
      </div>
      <?php } ?>

这样控制器中就不用再管这种无聊的事情,而集中精力负责业务逻辑和核心数据的调用了。

2016-09-17 注:

不记得当时是怎么走通的了,最新的2.3.系列中视图已经无法访问registry对象,需要做一些改造:

代码详见:https://github.com/web3d/yuncart/commit/923fb3257fb313fc7ce9b6ba379d1fb3176246cd

最终的用法,详见代码:

https://github.com/web3d/yuncart/commit/21bf845ffc31c4d724df1fc08d0f91cba353303d

改造后,虽然可以访问registry容器中所有组件,但建议只使用与视图相关的一些组件,如language、url、document。

原文地址:https://www.cnblogs.com/x3d/p/opencart-mvc-issue.html