Anyone, please help for me this issue. I'm the newbie of Doctrine. After some time to configure the doctrine(version 2.3) working with zend(version 1.10.8). All working fine except the last step. I have a table "test table" like this
CREATE TABLE IF NOT EXISTS `testtable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;
INSERT INTO `testtable` (`id`, `name`) VALUES
(1, 'test1'),
(2, 'what');
This is the Entity annotations
<?php
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table(name="testtable")
* #ORM\Entity
*
*/
class Tallcat_Doctrine_Entity_Test
{
/**
* #ORM\Column(type="string")
*/
private $name;
/**
* #ORM\Id #ORM\Column
* #ORM\GeneratedValue
*/
private $id;
/**
* #param string $name
*/
public function setName($name)
{
$this->name = (string)$name;
}
/**
* #return string
*/
public function getName()
{
return $this->name;
}
}
And in the controller of zend, i call this for testing:
class DoctrineController extends Zend_Controller_Action
{
protected $em = null;
public function init()
{
$this->em = \Zend_Registry::get('doctrine')->getEntityManager();
}
public function indexAction()
{
try{
$test = new Tallcat_Doctrine_Entity_Test();
$testMap = $this->em->getRepository('Tallcat_Doctrine_Entity_Test')- >findAll();
echo '<pre>';
print_r($testMap);
echo '</pre>';
die();
}catch(Exception $ex) {
print_r($ex);die();
}
}
}
And this is the result:
Array
(
[0] => Tallcat_Doctrine_Entity_Test Object
(
[name:Tallcat_Doctrine_Entity_Test:private] =>
[id:Tallcat_Doctrine_Entity_Test:private] => 1
)
[1] => Tallcat_Doctrine_Entity_Test Object
(
[name:Tallcat_Doctrine_Entity_Test:private] =>
[id:Tallcat_Doctrine_Entity_Test:private] => 2
)
)
I don't know what wrong with the file name, it cannot load. I tried to save one record, it can save the Id, except the file Name.
Someone could help please.
I solved it myself. The problem is:
The Doctrine cached the mapping before load, so the old code didn't update. So i restart the computer(stupid way) to clear cache. And it works perfect.
Thanks
Related
I'm new to Symfony and Doctrine and using the latest versions, am trying to create a Model with two key fields (attributes) for different purposes. $id is not the Primary Key but is AUTO_INCREMENT in MySQL/MariaDB. $key is string length=100 mapped to CHAR[100] and is the primary key and #ORM\Id. Even though this is what I'm trying to do, I don't think it's a supported configuration. I want to be able to merge() using key but also want to have the AI column for references (joining) because in part as I think it will have better performance, and even if not I want it anyway :) The thing is the data source which I use to populate may send multiple objects with the same key in which case I want them to persist to the same record, the last object the last to update the db, no duplicate keys.
I read somewhere, to use the DB implementation of AI and on non primary key, I may have to write a custom Hydrator. I have little idea what files to create and where to put them, and what mapping I have to do, or how exactly to do it. Hope someone can help.
<?php
// src/Entity/View.php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\ViewRepository")
*/
class View
{
/**
* #ORM\Column(type="integer", name="created_by")
*/
private $created_by;
/**
* #ORM\Column(type="integer", name="updated_by")
*/
private $updated_by;
/**
* #ORM\Column(type="bigint", name="id")
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #ORM\Id
* #ORM\Column(type="string", length=100, name="`key`")
*/
private $key;
/**
* #ORM\Column(type="json", name="`value`")
*/
private $value;
public function getCreatedBy()
{
return $this->created_by;
}
public function setCreatedBy($value)
{
$this->created_by = $value;
}
public function getUpdatedBy()
{
return $this->updated_by;
}
public function setUpdatedBy($value)
{
$this->updated_by = $value;
}
public function getId()
{
return $this->id;
}
public function setId($value)
{
$this->id = $value;
}
public function getKey()
{
return $this->key;
}
public function setKey($value)
{
$this->key = $value;
}
public function getValue()
{
return $this->value;
}
public function setValue($value)
{
$this->value = $value;
}
}
/* View */
CREATE TABLE IF NOT EXISTS `View` (
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_by INT UNSIGNED NOT NULL,
updated_by INT UNSIGNED NOT NULL,
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`key` CHAR(100) NOT NULL,
`value` JSON NOT NULL,
PRIMARY KEY PK_VIEW (`key`),
UNIQUE KEY UQ_VIEW (id)
) CHARSET = latin1;
$entity = new View();
$entity->setCreatedBy(0);
$entity->setUpdatedBy(0);
$entity->setKey($messageId);
$entity->setValue($json);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->merge($entity);
$entityManager->flush();
I'm facing what I think is a really easy task (or it should be at least), I've seen a lot of related questions and try to resolve my own problem with them with no luck at all, this is why I'm writing my own question here.
I want to be able to gather the average temperature from my table within the last 7 rows, i.e the average temperature for the last 7 days.
If I query my database using this simple query I obtain a result that matches my requirements:
select avg(m.temperatura) as temperature from (SELECT temperatura from database.meteodata order by indice desc limit 7) m
But, the problem is trying to move that query into doctrine with PHP.
I'm new to doctrine. I'm building a API using slim framework (version 3). I have a database with a table following this schema:
CREATE TABLE `meteodata` (
'indice' int(11) NOT NULL AUTO_INCREMENT,
'timestamp' timestamp NULL DEFAULT NULL,
'temperatura' float DEFAULT NULL,
'humedad' float DEFAULT NULL,
'viento' float NOT NULL,
'direccion_viento' int(11) NOT NULL,
'lluvia' float NOT NULL,
'summary' varchar(100) DEFAULT NULL,
'icon' varchar(45) DEFAULT NULL,
PRIMARY KEY ('indice')
) ENGINE=InnoDB AUTO_INCREMENT=562 DEFAULT CHARSET=latin1;
I also have an entity class to match that table into my PHP classes like following:
use Doctrine\ORM\Mapping as ORM;
/** #ORM\Entity()
* #ORM\Table(name="meteodata")
*/
class MeteoStation implements JsonSerializable
{
/** #ORM\Id()
* #ORM\Column(name="indice", type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $indice;
/** #ORM\Column(type="datetime", nullable=false) */
protected $timestamp;
/** #ORM\Column(name="viento", type="float") */
protected $wind;
/** #ORM\Column(name="temperatura", type="float") */
protected $temperature;
/** #ORM\Column(name="humedad", type="float") */
protected $humidity;
/** #ORM\Column(name="lluvia", type="float") */
protected $rain;
/** #ORM\Column(name="direccion_viento", type="integer") */
protected $dirViento;
/** #ORM\Column(length=100) */
protected $summary;
/** #ORM\Column(length=20) */
protected $icon;
/**
* #return mixed
*/
public function getIndice()
{
return $this->indice;
}
/**
* #param mixed $indice
*/
public function setIndice($indice)
{
$this->indice = $indice;
}
/**
* #return mixed
*/
public function getTimestamp()
{
return $this->timestamp;
}
/**
* #param mixed $timestamp
*/
public function setTimestamp($timestamp)
{
$this->timestamp = $timestamp;
}
/**
* #return mixed
*/
public function getWind()
{
return $this->wind;
}
/**
* #param mixed $wind
*/
public function setWind($wind)
{
$this->wind = $wind;
}
/**
* #return mixed
*/
public function getTemperature()
{
return $this->temperature;
}
/**
* #param mixed $temperature
*/
public function setTemperature($temperature)
{
$this->temperature = $temperature;
}
/**
* #return mixed
*/
public function getHumidity()
{
return $this->humidity;
}
/**
* #param mixed $humidity
*/
public function setHumidity($humidity)
{
$this->humidity = $humidity;
}
/**
* #return mixed
*/
public function getRain()
{
return $this->rain;
}
/**
* #param mixed $rain
*/
public function setRain($rain)
{
$this->rain = $rain;
}
/**
* #return mixed
*/
public function getDirViento()
{
return $this->dirViento;
}
/**
* #param mixed $dirViento
*/
public function setDirViento($dirViento)
{
$this->dirViento = $dirViento;
}
/**
* #return mixed
*/
public function getSummary()
{
return $this->summary;
}
/**
* #param mixed $summary
*/
public function setSummary($summary)
{
$this->summary = $summary;
}
/**
* #return mixed
*/
public function getIcon()
{
return $this->icon;
}
/**
* #param mixed $icon
*/
public function setIcon($icon)
{
$this->icon = $icon;
}
public function jsonSerialize()
{
return [
"index" => $this->getIndice(),
"timestamp" => $this->getTimestamp(),
"wind" => $this->getWind(),
"temperature" => $this->getTemperature(),
"humidity" => $this->getHumidity(),
"wind_direction" => $this->getDirViento(),
"rain" => $this->getRain(),
"summary" => $this->getSummary(),
"icon" => $this->getIcon()
];
}
}
The problem here is that the return result is always null.
I have a repository field with this method:
public function getLastAvgTemp()
{
$rsm = new ResultSetMappingBuilder($this->entityManager);
$rsm->addRootEntityFromClassMetadata('MeteoStation', 'm');
$rsm->addFieldResult('m', 'temperatura', 'temperature');
$query = $this->entityManager->createNativeQuery("select avg(m.temperatura) as temperatura from (SELECT temperatura from vinesens.meteodata order by indice desc limit 7) m", $rsm);
$data = $query->getResult();
var_dump($data);
//return $data;
}
The result is
nullarray(1) {
[
0
]=>
NULL
}
I know it has to be something easy, because if I change the query to this one (just retrieving the last 7 data) (I know it would be done differently it's just for the sake of the question)
$rsm = new ResultSetMappingBuilder($this->entityManager);
$rsm->addRootEntityFromClassMetadata('MeteoStation', 'm');
$rsm->addFieldResult('m', 'temperatura', 'temperature');
$query = $this->entityManager->createNativeQuery("select * from (SELECT * from vinesens.meteodata order by indice desc limit 7) m", $rsm);
$data = $query->getResult();
var_dump($data);
Then it returns all my values with the appropriate data.
So I think it has something to do with selecting only one particular column from the table and I don't know how to fix it because if I change the query to this:
$rsm = new ResultSetMappingBuilder($this->entityManager);
$rsm->addRootEntityFromClassMetadata('MeteoStation', 'm');
$rsm->addFieldResult('m', 'temperatura', 'temperature');
$query = $this->entityManager->createNativeQuery("select m.temperatura as temperatura from (SELECT temperatura from vinesens.meteodata order by indice desc limit 7) m", $rsm);
$data = $query->getResult();
var_dump($data);
It returns 7 null objects like so:
array(7) {
[
0
]=>
NULL
[
1
]=>
NULL
[
2
]=>
NULL
[
3
]=>
NULL
[
4
]=>
NULL
[
5
]=>
NULL
[
6
]=>
NULL
}
Please, if you need more information don't hesitate to ask me.
Thank you so much.
Hopefully i am asking this on the right stack exchange forum. If not please do let me know and I will ask somewhere else. I have also asked on Code Review, but the community seems a lot less active.
As I have self learned PHP and all programming in general, I have only recently found out about 'Data Mappers' which allows data to be passed into classes without said classes knowing where the data comes from. I have read some of the positives of using mappers and why they make it 'easier' to perform upgrades later down the line, however I am really struggling to find out the reccomended way of using mappers and their layouts in a directory structure.
Let's assume we have a simple application whos purpose is to echo out a first name and last name of a user.
The way I have been using/creating mappers (as well as the file structure is as follows):
index.php
include 'classes/usermapper.php';
include 'classes/user.php';
$user = new User;
$userMapper = new userMapper;
try {
$user->setData([
$userMapper->fetchData([
'username'=>'peter1'
])
]);
} catch (Exception $e) {
die('Error occurred');
}
if ($user->hasData()) {
echo $user->fullName();
}
classes/user.php
class User {
private $_data;
public function __construct() { }
public function setData($userObject = null) {
if (!$userObject) { throw new InvalidArgumentException('No Data Set'); }
$this->_data = $dataObject;
}
public function hasData() {
return (!$this->_data) ? false : true;
}
public function fullName() {
return ucwords($this->_data->firstname.' '.$this->_data->lastname);
}
}
classes/usermapper.php
class userMapper {
private $_db;
public function __construct() { $this->_db = DB::getInstance(); }
public function fetchData($where = null) {
if (!is_array($where)) {
throw new InvalidArgumentException('Invalid Params Supplied');
}
$toFill = null;
foreach($where as $argument=>$value) {
$toFill .= $argument.' = '.$value AND ;
}
$query = sprintf("SELECT * FROM `users` WHERE %s ", substr(rtrim($toFill), 0, -3));
$result = $this->_db->query($query); //assume this is just a call to a database which returns the results of the query
return $result;
}
}
With understanding that the users table contains a username, first name and last name, and also that a lot of sanitizing checks are missing, why are mappers convenient to use?
This is a very long winded way in getting data, and assuming that users aren't everything, but instead orders, payments, tickets, companies and more all have their corresponding mappers, it seems a waste not to create just one mapper and implement it everywhere in each class.
This allows the folder structure to look a whole lot nicer and also means that code isn't repeated as often.
The example mappers looks the same in every case bar the table the data is being pulled from.
Therefore my question is. Is this how data mappers under the 'domain model mappers' should look like, and if not how could my code be improved? Secondly is this model needed in all cases of needing to pull data from a database, regardless of the size of class, or should this model only be used where the user.php class in this case is very large?
Thank you in advance for all help.
The Data Mapper completely separates the domain objects from the persistent storage (database) and provides methods that are specific to domain-level operations. Use it to transfer data from the domain to the database and vice versa. Within a method, a database query is usually executed and the result is then mapped (hydrated) to a domain object or a list of domain objects.
Example:
The base class: Mapper.php
abstract class Mapper
{
protected $db;
public function __construct(PDO $db)
{
$this->db = $db;
}
}
The file: BookMapper.php
class BookMapper extends Mapper
{
public function findAll(): array
{
$sql = "SELECT id, title, price, book_category_id FROM books;";
$statement = $this->db->query($sql);
$items = [];
while ($row = $statement->fetch()) {
$items[] = new BookEntity($row);
}
return $items;
}
public function findByBookCategoryId(int $bookCategoryId): array
{
$sql = "SELECT id, title, price, book_category_id
FROM books
WHERE book_category_id = :book_category_id;";
$statement = $this->db->prepare($sql);
$statement->execute(["book_category_id" => $bookCategoryId]);
$items = [];
while ($row = $statement->fetch()) {
$items[] = new BookEntity($row);
}
return $items;
}
/**
* Get one Book by its ID
*
* #param int $bookId The ID of the book
* #return BookEntity The book
* #throws RuntimeException
*/
public function getById(int $bookId): BookEntity
{
$sql = "SELECT id, title, price, book_category_id FROM books
WHERE id = :id;";
$statement = $this->db->prepare($sql);
if (!$result = $statement->execute(["id" => $bookId])) {
throw new DomainException(sprintf('Book-ID not found: %s', $bookId));
}
return new BookEntity($statement->fetch());
}
public function insert(BookEntity $book): int
{
$sql = "INSERT INTO books SET title=:title, price=:price, book_category_id=:book_category_id";
$statement = $this->db->prepare($sql);
$result = $statement->execute([
'title' => $book->getTitle(),
'price' => $book->getPrice(),
'book_category_id' => $book->getBookCategoryId(),
]);
if (!$result) {
throw new RuntimeException('Could not save record');
}
return (int)$this->db->lastInsertId();
}
}
The file: BookEntity.php
class BookEntity
{
/** #var int|null */
protected $id;
/** #var string|null */
protected $title;
/** #var float|null */
protected $price;
/** #var int|null */
protected $bookCategoryId;
/**
* Accept an array of data matching properties of this class
* and create the class
*
* #param array|null $data The data to use to create
*/
public function __construct(array $data = null)
{
// Hydration (manually)
if (isset($data['id'])) {
$this->setId($data['id']);
}
if (isset($data['title'])) {
$this->setTitle($data['title']);
}
if (isset($data['price'])) {
$this->setPrice($data['price']);
}
if (isset($data['book_category_id'])) {
$this->setBookCategoryId($data['book_category_id']);
}
}
/**
* Get Id.
*
* #return int|null
*/
public function getId(): ?int
{
return $this->id;
}
/**
* Set Id.
*
* #param int|null $id
* #return void
*/
public function setId(?int $id): void
{
$this->id = $id;
}
/**
* Get Title.
*
* #return null|string
*/
public function getTitle(): ?string
{
return $this->title;
}
/**
* Set Title.
*
* #param null|string $title
* #return void
*/
public function setTitle(?string $title): void
{
$this->title = $title;
}
/**
* Get Price.
*
* #return float|null
*/
public function getPrice(): ?float
{
return $this->price;
}
/**
* Set Price.
*
* #param float|null $price
* #return void
*/
public function setPrice(?float $price): void
{
$this->price = $price;
}
/**
* Get BookCategoryId.
*
* #return int|null
*/
public function getBookCategoryId(): ?int
{
return $this->bookCategoryId;
}
/**
* Set BookCategoryId.
*
* #param int|null $bookCategoryId
* #return void
*/
public function setBookCategoryId(?int $bookCategoryId): void
{
$this->bookCategoryId = $bookCategoryId;
}
}
The file: BookCategoryEntity.php
class BookCategoryEntity
{
const FANTASY = 1;
const ADVENTURE = 2;
const COMEDY = 3;
// here you can add the setter and getter methods
}
The table structure: schema.sql
CREATE TABLE `books` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`price` decimal(19,2) DEFAULT NULL,
`book_category_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `book_category_id` (`book_category_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `book_categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*Data for the table `book_categories` */
insert into `book_categories`(`id`,`title`) values (1,'Fantasy');
insert into `book_categories`(`id`,`title`) values (2,'Adventure');
insert into `book_categories`(`id`,`title`) values (3,'Comedy');
Usage
// Create the database connection
$host = '127.0.0.1';
$dbname = 'test';
$username = 'root';
$password = '';
$charset = 'utf8';
$collate = 'utf8_unicode_ci';
$dsn = "mysql:host=$host;dbname=$dbname;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => false,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES $charset COLLATE $collate"
];
$db = new PDO($dsn, $username, $password, $options);
// Create the data mapper instance
$bookMapper = new BookMapper($db);
// Create a new book entity
$book = new BookEntity();
$book->setTitle('Harry Potter');
$book->setPrice(29.99);
$book->setBookCategoryId(BookCategoryEntity::FANTASY);
// Insert the book entity
$bookId = $bookMapper->insert($book);
// Get the saved book
$newBook = $bookMapper->getById($bookId);
var_dump($newBook);
// Find all fantasy books
$fantasyBooks = $bookMapper->findByBookCategoryId(BookCategoryEntity::FANTASY);
var_dump($fantasyBooks);
When creating an eloquent model:
Model::create(['prop1' => 1, 'prop2' => 2]);
the returned model will only have prop1 & prop2 as properties, what can I do to eager load all others properties that I haven't inserted in database because they are optional ?
EDIT: Why do I need this ? to rename my database fields:
database
CREATE TABLE `tblCustomer` (
`pkCustomerID` INT(11) NOT NULL AUTO_INCREMENT,
`baccount` VARCHAR(400) NULL DEFAULT NULL,
`fldName` VARCHAR(400) NULL DEFAULT NULL,
`fldNumRue` VARCHAR(10) NULL DEFAULT NULL,
....
PRIMARY KEY (`pkCustomerID`)
);
customer model
<?php namespace App\Models;
/**
* Class Customer
* #package App\Models
* #property int code
* #property string name
* #property string addressno
*/
class Customer extends Model
{
protected $table = 'tblCustomer';
protected $primaryKey = 'pkCustomerID';
public $timestamps = false;
/**
* The model's attributes.
* This is needed as all `visible fields` are mutators, so on insert
* if a field is omitted, the mutator won't find it and raise an error.
* #var array
*/
protected $attributes = [
'baccount' => null,
'fldName' => null,
'fldNumRue' => null,
];
/**
* The accessors to append to the model's array form.
* #var array
*/
protected $appends = [
'id',
'code',
'name',
'addressno'
];
public function __construct(array $attributes = [])
{
// show ONLY mutators
$this->setVisible($this->appends);
parent::__construct($attributes);
}
public function setAddressnoAttribute($value)
{
$this->attributes['fldNumRue'] = $value;
return $this;
}
public function getAddressnoAttribute()
{
return $this->attributes['fldNumRue'];
}
}
The problem is that when Laravel converts everything to JSON, he will parse all my mutators:
public function getAddressnoAttribute()
{
return $this->attributes['fldNumRue'];
}
and raise an error as $this->attributes['fldNumRue'] is not defined ErrorException: Undefined index... So I need a way to initialize all attributes with their default values.
You can call fresh() method on your model. It will reload the model from the database and return it. Keep in mind that it returns a reloaded object - it doesn't update existing one. You can also pass an array of relations that should be reloaded:
$model = $model->fresh($relations);
You could consider removing default values from the database and in your model. This way you won't need to reload model to get the defaults.
You can do it by overriding $attributes property in your model and seting defaults there:
class MyModel extends Model {
protected $attributes = [
'key' => 'default value'
];
}
A Doctrine 2 Entity with a composite key:
/**
* #Entity
*/
class Test
{
/**
* #Id
* #Column (type="integer", length=11, name="id")
*
*/
protected $id = null;
/**
* #Id
* #Column (type="integer", length=11, name="idtwo")
*
*/
protected $idtwo = null;
public function setIdTwo($id)
{
$this->idtwo = $id;
}
public function setId($id)
{
$this->id = $id;
}
}
Saving the Entity
$test = new Test();
$test->setId(1);
$test->setIdTwo(1);
$em->persist($test);
DB Table:
CREATE TABLE `Bella_Test` (
`id` int(11) NOT NULL,
`idtwo` int(11) NOT NULL,
PRIMARY KEY (`id`,`idtwo`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Expected result: a row is added to the db table with two id fields, both with a value of 1.
Actual result: No row is added to the db table. No exception is thrown.
Question: What is going on?
You can use a try catch block to see what happens
try{
$em->flush(); //don't forget flush after persisting an object
}
catch(Exception $e){
echo 'Flush Operation Failed: '.$e->getMessage();
}
Other assumption, in my opinion, your entity table name and DB table name may not match each other. I think it's not a bad idea to give a try
/**
* #Entity
* #Table(name="Bella_Test")
*/
.
.
.