openbuildings/jam-locations

Geoip和IP集成

0.2.1 2020-03-02 14:07 UTC

This package is auto-updated.

Last update: 2024-08-29 04:04:03 UTC


README

Build Status Coverage Status Latest Stable Version

此模块通过利用openbuildings/jam-closuretable添加分层位置(大洲、国家、城市)。同时,通过地理位置自动初始化IP字段和自动设置国家/城市。

用法

使用IP字段就像定义它一样简单

class Model_User extends Jam_Model {

	public static function initialize(Jam_Meta $meta)
	{
		$meta
			->fields(array(
				// ...
				'ip' => Jam::field('ip'),
			));
	}
}

$user = Jam::build('user');
echo $user->ip; // will return the current ip address (from Request::$clent_ip)

自动定位稍微复杂一些

class Model_User extends Jam_Model {

	public static function initialize(Jam_Meta $meta)
	{
		$meta
			->behaviors(array(
				'location_auto' => Jam::behavior('location_auto', array(
					'locations' => array(
						// association => geoip record name
						'city' => 'city',
						'country' => 'country_name',
					)
				)),
			))
			->associations(array(
				'country' => Jam::association('belongsto', array('foreign_model' => 'location')),
				'city' => Jam::association('belongsto', array('foreign_model' => 'location')),
			))
			->fields(array(
				'id' => Jam::field('primary'),
				'ip' => Jam::field('ip'),
			));
	}
}

然后,如果您没有设置城市或国家关联,它将使用IP字段获取geoip记录,并从中尝试找到/创建适当的位置。

最后,使用location_parent行为将父级分配给模型中存在的位置关联

class Model_Address extends Jam_Model {

	public static function initialize(Jam_Meta $meta)
	{
		$meta
			->behaviors(array(
				'location_parent' => Jam::behavior('location_parent', array(
					'parents' => array(
						// child => parent
						'city' => 'country',
					)
				)),
			))
			->associations(array(
				'country' => Jam::association('belongsto', array('foreign_model' => 'location')),
				'city' => Jam::association('belongsto', array('foreign_model' => 'location')),
			))
			->fields(array(
				'id' => Jam::field('primary'),
			));
	}
}

$address = Jam::build('address');

$address->country = Jam::find('location', 'France');
$address->city = Jam::build('location', array('name' => 'Paris'));

$address->save();

echo $address->city->parent->name(); // will return "France"

需求

此模块需要php geoip扩展。

许可协议

版权(c)2012-2013,OpenBuildings Ltd。由Ivan Kerin开发,作为clippings.com的一部分。

在BSD-3-Clause许可下,请参阅LICENSE文件。