Skip to content

Class: Nether\Object\Mapped

Bob Magic II edited this page Aug 10, 2021 · 8 revisions

NOTE: THIS CLASS IS DEPRECATED.
It is preferred that Nether\Object\Prototype is used instead.

This class provides built in schema translation and default property filling. Using the colon syntax on the destination names the class will handle typecasting those properties into those types for you automatically. Typecasting only works with the core PHP primitive types.

$Object = new Nether\Object\Mapped(
	array|object|null $Mapped,
	array|object|null $Defaults,
	array|null $Options
);

Usage With PropertyMap

class User
extends Nether\Object\Mapped {

	static protected
	$PropertyMap = [
		'user_id'    => 'ID:int',
		'user_name'  => 'Name',
		'user_email' => 'Email',
		'user_title' => 'Title'
	];

}

$RowFromDB = [
	'user_id'    => '1',
	'user_name'  => 'bob',
	'user_email' => 'bmajdak-at-php-dot-net',
	'user_title' => 'Chief Iconoclast'
];

var_dump(new User($RowFromDB));
object(User)#3 (4) {
	["ID"]=> int(1)
	["Name"]=> string(3) "bob"
	["Email"]=> string(22) "bmajdak-at-php-dot-net"
	["Title"]=> string(16) "Chief Iconoclast"
}

Usage With Default Values

The second argument to the constructor is an array of default values that should be filled into the object if the data source was missing something. In this example our MySQL data had no user_status field.

class User
extends Nether\Object\Mapped {

	static protected
	$PropertyMap = [
		'user_id'     => 'ID:int',
		'user_name'   => 'Name',
		'user_email'  => 'Email',
		'user_title'  => 'Title',
		'user_status' => 'Status'
	];

}

$RowFromDB = [
	'user_id'    => '1',
	'user_name'  => 'bob',
	'user_email' => 'bmajdak-at-php-dot-net',
	'user_title' => 'Chief Iconoclast'
];

$Defaults = [
	'Status' => 'Probably Cool'
];

var_dump(new User($RowFromDB));
var_dump(new User($RowFromDB, $Defaults));
object(User)#4 (4) {
	["ID"]=> int(1)
	["Name"]=> string(3) "bob"
	["Email"]=> string(22) "bmajdak-at-php-dot-net"
	["Title"]=> string(16) "Chief Iconoclast"
}

object(User)#5 (5) {
	["ID"]=> int(1)
	["Name"]=> string(3) "bob"
	["Email"]=> string(22) "bmajdak-at-php-dot-net"
	["Title"]=> string(16) "Chief Iconoclast"
	["Status"]=> string(13) "Probably Cool"
}