我正在为我们遗留的网络商店开发一个集中的管理软件。这些商店是由第三方开发的,而且相当古老,所以他们也采用了相当古老的做法。Orders及其相关对象存储在一个表中,因此该表有很多字段,并且非常臃肿。我们的新管理系统采用了一种关系方法。也就是说,我有一个表order来存储订单,一个表address用来存储所有地址。每个order通过外键引用其发货和计费地址。理论2用于处理这些实体及其关系。
显然,我必须将商店的订单导入我们管理系统的数据库中。这是通过直接访问每个商店的数据库,查询订单数据并将其插入管理系统自己的数据库中来实现的。
我正在使用ZF2 TableGateway从商店中检索数据,我想用Doctrine的DoctrineObject消火栓给我的实体补水,尽可能少的处理。但是,DoctrineObject消火栓希望在嵌套数组中传递相关的对象。因为我还没有弄清楚TableGateway是否能产生多维结果,所以在将接收到的数据传递给消防栓之前,我必须手动处理它。
// $shop_db is a configured \Zend\Db\Adapter\Adapter to
// access the shop's database
$orders_table = new TableGateway(['order' => 'shop_orders'], $shop_db);
$order_data = $orders_table
    ->select(
        function(Select $select) {
            $select->columns([
                // Note: I am renaming the source fields to 
                // their internal equivalent via aliases
                'source_order_id' => 'id',
                'remarks' => 'customer_remarks',
                'created_at' => 'order_date',
                // Prefix the shipping address data with
                // "shipping_address_" so we can easily 
                // extract it later
                'shipping_address_firstname' => 'safirst',
                'shipping_address_lastname' => 'salast',
                'shipping_address_company' => 'sacomp',
                'shipping_address_street' => 'sastreet',
                'shipping_address_zip_code' => 'sazip',
                'shipping_address_city' => 'sacity'
            ]);
            $select->order('id');
        }
    );
// Process each order so its data can be
// digested by the DoctrineObject hydrator
foreach($order_data as $order)
{
    // ...
    // extract each element that has the 
    // prefix "shipping_address_" from the $order
    // and copy it to a nested array $order['shipping_address']
    // ...
}因此,为了避免手工处理,我可以想到两种可能的解决方案:
TableGatway返回多维结果的方法DoctrineHydrator能够通过前缀数组元素而不是嵌套数组填充相关对象的方法。几年前,我们一直在使用Propel2,如果我没记错的话,Propel的水龙头可以通过前缀自动从一维数组中填充相关对象,这与我手动处理接收到的数据的方式非常相似。据我所见,原则消防栓无法做到这一点,尽管我想你可以使用策略来完成这一任务。
在深入研究开发策略或派生TableGateway之前,有人知道开箱即用的解决方案吗?还是我目前的方法是它能得到的最好的?
发布于 2016-09-23 12:20:54
我认为您当前将数据映射到您的消火栓所期望的格式的过程将更适合于使用命名策略(因为您有一个平面数组,而水龙头需要一个嵌套的数组)。
您甚至可以创建一个复合水龙头来封装映射。
class MyHydrator implements HydratorInterface
{
    // The class that does the data conversion
    protected $mapper;
    // The doctrine hydrator
    protected $hydrator;
    public function hydrate($data, $object)
    {
        // Return the data to the format that is expected
        $data = $this->mapper->map($data);
        return $this->hydrator->hydrate($data, $object);
    }
    public function extract($object)
    {
        $data = $this->hydrator->extract($object);
        // Reverse the data into a flat structure
        return $this->mapper->unmap($data);
    }
}https://stackoverflow.com/questions/39641556
复制相似问题