PHP - Stupid Mistake With Doctrine Entities And Inheritance
I am doing something stupid, and just can't see it and hoping someone has better eyes than mine. I have two Doctrine entities which extend another class using single class inheritance, but when retrieving the collection of either of the two child classes, I get the collection of the parent (i.e. combination of both child classes). I've experimented with making the parent abstract and not including it in the discriminator map but no change. In hopes to identifying my mistake, I created a new Symfony project with just the relevant classes and show all steps below. Initial install by running the following: symfony new test composer update composer require doctrine/orm composer require migrations composer require maker --dev composer require security Using "php bin/console make:user", I created three users: AbstractUser, OwnerUser, VendorUser. I then edited all three entities and the owner and vendor repositories as follows: <?php namespace App\Entity; use App\Repository\AbstractUserRepository; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Security\Core\User\UserInterface; /** * @ORM\Entity(repositoryClass=AbstractUserRepository::class) * @ORM\InheritanceType("SINGLE_TABLE") * @ORM\DiscriminatorColumn(name="discr", type="string") * @ORM\DiscriminatorMap({"owner" = "OwnerUser", "vendor" = "VendorUser", "abstract" = "AbstractUser"}) */ class AbstractUser implements UserInterface { // No changes made }
<?php namespace App\Entity; use App\Repository\OwnerUserRepository; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=OwnerUserRepository::class) */ class OwnerUser extends AbstractUser { }
<?php namespace App\Entity; use App\Repository\VendorUserRepository; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=VendorUserRepository::class) */ class VendorUser extends AbstractUser { } No change to AbstractUserRepository. <?php namespace App\Repository; class OwnerUserRepository extends AbstractUserRepository { }
<?php namespace App\Repository; class VendorUserRepository extends AbstractUserRepository { } Then I migrated the DB. php bin/console doctrine:schema:drop --full-database --force rm migrations/* php bin/console make:migration php bin/console doctrine:migrations:migrate Next I created two OwnerUsers and one VendorUser using a command script I wrote shown at the end of this post. # php bin/console app:tester create OwnerUser roles=[] # php bin/console app:tester create OwnerUser roles=[] # php bin/console app:tester create VendorUser roles=[] Checked the PostSQL database. facdocs=> \d List of relations Schema | Name | Type | Owner --------+-----------------------------+----------+--------- public | abstract_user | table | facdocs public | abstract_user_id_seq | sequence | facdocs public | doctrine_migration_versions | table | facdocs (3 rows) facdocs=> select * from abstract_user; id | email | roles | password | discr ----+-------------+-------+----------------+-------- 1 | setEmail158 | [] | setPassword146 | owner 2 | setEmail87 | [] | setPassword101 | owner 3 | setEmail62 | [] | setPassword20 | vendor (3 rows) facdocs=>
Next, I retrieved the entities using Doctrine along with the beforementioned test script. [michael@devserver test]$ php bin/console app:tester read VendorUser Test Entity Manager ============ command: read entity: VendorUser class: \App\Entity\VendorUser properties: [] array(3) { [0]=> object(stdClass)#293 (5) { ["__CLASS__"]=> string(20) "App\Entity\OwnerUser" ["id:App\Entity\AbstractUser:private"]=> int(1) ["email:App\Entity\AbstractUser:private"]=> string(11) "setEmail158" ["roles:App\Entity\AbstractUser:private"]=> string(8) "Array(0)" ["password:App\Entity\AbstractUser:private"]=> string(14) "setPassword146" } [1]=> object(stdClass)#294 (5) { ["__CLASS__"]=> string(20) "App\Entity\OwnerUser" ["id:App\Entity\AbstractUser:private"]=> int(2) ["email:App\Entity\AbstractUser:private"]=> string(10) "setEmail87" ["roles:App\Entity\AbstractUser:private"]=> string(8) "Array(0)" ["password:App\Entity\AbstractUser:private"]=> string(14) "setPassword101" } [2]=> object(stdClass)#358 (5) { ["__CLASS__"]=> string(21) "App\Entity\VendorUser" ["id:App\Entity\AbstractUser:private"]=> int(3) ["email:App\Entity\AbstractUser:private"]=> string(10) "setEmail62" ["roles:App\Entity\AbstractUser:private"]=> string(8) "Array(0)" ["password:App\Entity\AbstractUser:private"]=> string(13) "setPassword20" } } [michael@devserver test]$ [michael@devserver test]$ php bin/console app:tester read OwnerUser Test Entity Manager ============ command: read entity: OwnerUser class: \App\Entity\OwnerUser properties: [] array(3) { [0]=> object(stdClass)#293 (5) { ["__CLASS__"]=> string(20) "App\Entity\OwnerUser" ["id:App\Entity\AbstractUser:private"]=> int(1) ["email:App\Entity\AbstractUser:private"]=> string(11) "setEmail158" ["roles:App\Entity\AbstractUser:private"]=> string(8) "Array(0)" ["password:App\Entity\AbstractUser:private"]=> string(14) "setPassword146" } [1]=> object(stdClass)#294 (5) { ["__CLASS__"]=> string(20) "App\Entity\OwnerUser" ["id:App\Entity\AbstractUser:private"]=> int(2) ["email:App\Entity\AbstractUser:private"]=> string(10) "setEmail87" ["roles:App\Entity\AbstractUser:private"]=> string(8) "Array(0)" ["password:App\Entity\AbstractUser:private"]=> string(14) "setPassword101" } [2]=> object(stdClass)#358 (5) { ["__CLASS__"]=> string(21) "App\Entity\VendorUser" ["id:App\Entity\AbstractUser:private"]=> int(3) ["email:App\Entity\AbstractUser:private"]=> string(10) "setEmail62" ["roles:App\Entity\AbstractUser:private"]=> string(8) "Array(0)" ["password:App\Entity\AbstractUser:private"]=> string(13) "setPassword20" } } [michael@devserver test]$
As seen, when requesting a collection of either OwnerUsers or VendorUsers, I am retrieving the combination of both collections. I am sure it is totally user (i.e. me) error, but just don't see it. Are you able to see my stupid mistake? Thanks
<?php namespace App\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Input\InputArgument; use Doctrine\ORM\EntityManagerInterface; use Doctrine\Common\Util\Debug; class Tester extends Command { // the name of the command (the part after "bin/console") protected static $defaultName = 'app:tester'; private $entityManager; public function __construct(EntityManagerInterface $entityManager) { $this->entityManager = $entityManager; parent::__construct(); } protected function configure() { $this ->setDescription('Doctrine Object Tester. --help') ->setHelp('This command allows you to query a single entity...') ->addArgument('cmd', InputArgument::REQUIRED, 'The command name [create, read].') ->addArgument('entity', InputArgument::REQUIRED, 'The name of the entity.') ->addArgument('properties', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'properies (foo=foo bla=[]') ; } private function getProperties($input) { $properties=[]; foreach($input as $property) { $property=explode('=', $property); $name = trim($property[0]); $value = trim($property[1]); if($value === '[]') { $value = []; } elseif($value === 'null') { $value = null; } elseif(substr($value, 0, 1) === '/') { $value = explode('/', substr($value, 1)); $class = ucfirst(substr($value[0], 0, -1)); $class = '\App\Entity\\'.$class; if(count($value)===1) { $value = $this->entityManager->getRepository($class)->findAll(); } else { $value = $this->entityManager->getRepository($class)->find($value[1]); } } $properties[$name] = $value; } return $properties; } protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln([ 'Test Entity Manager', '============', '', ]); // retrieve the argument value using getArgument() $cmd = $input->getArgument('cmd'); $output->writeln('command: '.$cmd); $entity = $input->getArgument('entity'); $output->writeln('entity: '.$entity); $class = '\App\Entity\\'.$entity; $output->writeln('class: '.$class); $properties = $this->getProperties($input->getArgument('properties')); $output->writeln('properties: '.json_encode($properties)); switch($cmd) { case 'create': $entity = new $class; foreach(get_class_methods($entity) as $method) { if(substr($method, 0, 3)==='set') { $m = lcfirst(substr($method, 3)); $entity->$method(array_key_exists($m, $properties)?$properties[$m]:$method.rand(0,200)); } } $this->entityManager->persist($entity); $this->entityManager->flush(); $output->writeln('entity created'); break; case 'read': Debug::dump($this->entityManager->getRepository($class)->findAll()); break; default: $output->writeln('INVALID COMMAND: '.$cmd.'. Only create and read are supported.'); } return Command::SUCCESS; } }
Similar TutorialsI'm starting in Doctrine 2.4 and I'm developing a system where I separate the core files and application files, as follows:
/root |-- /Src |-- /App |-- /Model |-- ** (Application Entities) ** |-- /Core |-- /Model |-- ** (Core Entities) **In the Doctrine documentation shows the following form to set 1 directory for Esntitys: $config = Setup::createAnnotationMetadataConfiguration(array(__DIR__. "/src"), $isDevMode);But when I have to configure more than one directory that will contain the Entitys of my application, how to proceed? Thanks in advance! Trying to create a model where Parent1 and Parent2 extend Grandparent, and Child1_1 and Child1_2 extend Parent1 as well as Child2_1 and Child2_2 extend Parent2. I set up my definitions: Grandparent: type: entity table: grandparent_table inheritanceType: JOINED discriminatorColumn: name: discriminator_column_grandparent type: string repositoryClass: GrandParent id: id: type: integer generator: strategy: AUTO fields: GrandParent_Item1: type: string GrandParent_Item2: type: string Parent1: type: entity table: parent_table1 extends: Grandparent inheritanceType: JOINED discriminatorColumn: name: discriminator_column_parent1 type: string id: id: associationKey: true fields: Parent1_Item1: type: string Parent1_Item2: type: string Parent2: type: entity table: parent_table2 extends: Grandparent inheritanceType: JOINED discriminatorColumn: name: discriminator_column_parent2 type: string id: id: associationKey: true fields: Parent2_Item1: type: string Parent2_Item2: type: string Child1_1: extends: Parent1 type: entity table: child1_1_table id: id: associationKey: true fields: Child1_1_Item1: type: string Child1_1_Item2: type: string Child1_2: extends: Parent1 type: entity table: child1_2_table id: id: associationKey: true fields: Child1_2_Item1: type: string Child1_2_Item2: type: string Child2_1: extends: Parent2 type: entity table: child2_1_table id: id: associationKey: true fields: Child2_1_Item1: type: string Child2_1_Item2: type: string Child2_2: extends: Parent2 type: entity table: child2_2_table id: id: associationKey: true fields: Child2_2_Item1: type: string Child2_2_Item2: type: string And then generate my entities: $ vendor/bin/doctrine orm:generate-entities -vvv src Processing entity "Child1_1" Processing entity "Child1_2" Processing entity "Child2_1" Processing entity "Child2_2" Processing entity "Grandparent" Processing entity "Parent1" Processing entity "Parent2" [OK] Entity classes generated to "/var/www/doctrine/src" Note that I needed to manually edit the Parent1 and 2 classes to extend Grandparent as well as the individual Child classes to extend their applicable Parent. Next, I create the schema: $ vendor/bin/doctrine orm:schema-tool:create --dump-sql The following SQL statements will be executed: CREATE TABLE child1_1_table (id INT NOT NULL, Child1_1_Item1 VARCHAR(255) NOT NULL, Child1_1_Item2 VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB; CREATE TABLE child1_2_table (id INT NOT NULL, Child1_2_Item1 VARCHAR(255) NOT NULL, Child1_2_Item2 VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB; CREATE TABLE child2_1_table (id INT NOT NULL, Child2_1_Item1 VARCHAR(255) NOT NULL, Child2_1_Item2 VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB; CREATE TABLE child2_2_table (id INT NOT NULL, Child2_2_Item1 VARCHAR(255) NOT NULL, Child2_2_Item2 VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB; CREATE TABLE grandparent_table (id INT AUTO_INCREMENT NOT NULL, GrandParent_Item1 VARCHAR(255) NOT NULL, GrandParent_Item2 VARCHAR(255) NOT NULL, discriminator_column_grandparent VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB; CREATE TABLE parent_table1 (id INT NOT NULL, Parent1_Item1 VARCHAR(255) NOT NULL, Parent1_Item2 VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB; CREATE TABLE parent_table2 (id INT NOT NULL, Parent2_Item1 VARCHAR(255) NOT NULL, Parent2_Item2 VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB; ALTER TABLE child1_1_table ADD CONSTRAINT FK_3445750EBF396750 FOREIGN KEY (id) REFERENCES grandparent_table (id) ON DELETE CASCADE; ALTER TABLE child1_2_table ADD CONSTRAINT FK_5AD6F93BF396750 FOREIGN KEY (id) REFERENCES grandparent_table (id) ON DELETE CASCADE; ALTER TABLE child2_1_table ADD CONSTRAINT FK_DC849CBBF396750 FOREIGN KEY (id) REFERENCES grandparent_table (id) ON DELETE CASCADE; ALTER TABLE child2_2_table ADD CONSTRAINT FK_3C205356BF396750 FOREIGN KEY (id) REFERENCES grandparent_table (id) ON DELETE CASCADE; ALTER TABLE parent_table1 ADD CONSTRAINT FK_5386E15BBF396750 FOREIGN KEY (id) REFERENCES grandparent_table (id) ON DELETE CASCADE; ALTER TABLE parent_table2 ADD CONSTRAINT FK_CA8FB0E1BF396750 FOREIGN KEY (id) REFERENCES grandparent_table (id) ON DELETE CASCADE; I see how Grandparent has discriminatorColumn discriminator_column_grandparent as expected. But why doesn't Parent1 and Parent2 have discriminatorColumn's discriminator_column_parent1 and discriminator_column_parent2? Note that I've also tried making Grandparent, Parent1, and Parent2 abstract but get the same results. I've also messed around with Mapped Superclasses, but I don't think they are applicable for my use (correct me if you think I am wrong). Thanks! I wish to create and store in a DB three objects which are created using injection; $myAObject=new BaseEntity(new InjectedThingA()); $myBObject=new BaseEntity(new InjectedThingB()); $myCObject=new BaseEntity(new InjectedThingC()); BaseEntity is defined by SQL table base_entity and my three injected objects InjectedThingA, InjectedThingB, and InjectedThingC are each defined by SQL tables injected_thing_a, injected_thing_b, injected_thing_c, respectively. Each of these injected tables has autoincrement column id plus whatever other columns, and base_entity includes a column injected_thing_id. But this won't work since this ID is not unique across InjectedThings and also poor since there is no foreign key, so instead I do the following. InjectedThingA extends AbstractInjectedThing InjectedThingB extends AbstractInjectedThing InjectedThingC extends AbstractInjectedThing Then I add an autoincrement id column to AbstractedInjectedThing and place a one-to-one constraint from column id in InjectedThingA, InjectedThingB, and InjectedThingC to column id in AbstractedInjectedThing. So, I still need to use inheritance, right? I don't think that this type of inheritance brings the baggage which MyInheritedEntity extends BaseEntity does and I am okay with it, but just want to make sure I am doing this right. Thanks Edited October 4, 2019 by NotionCommotionI beleive that my code is "ok" overall, but i am getting a syntax error on lines 6 & 26, pretty sure im making a stupid mistake here, Code is a plugin for a PHP IRC Bot, basically a toggle on/off command via "!radio" to send meta data from the audio stream every 5minutes. <?php require_once('shoutcast_class.php'); $radio = false; class plugRadio{ public static function onCommandRadio( if($radio == false) $radio = true; $dh->reply('3 Info Stream : ON', $event->getName(), $dh->getCommandTrailing()); while($radio == true){ event $event, datahelper $dh = null, $help = 'use !Radio to toggle stream info On/Off') { $display_array = array("Stream Title", "Stream Genre", "Stream URL", "Current Song", "Server Status", "Stream Status", "Listener Peak", "Average Listen Time", "Stream Title", "Content Type", "Stream Genre", "Stream URL", "Current Song"); $radio = new Radio("radio.anonops.ru:8000"); $data_array = $radio->getServerInfo($display_array); $dh->reply('15,1 #RadioPayback | 9,1On Air: '.$data_array[8].' 15,1| 9,1Now Playing: '.$data_array[12].' ', $event->getName(), $dh->getCommandTrailing()); $event->delete(); flush(); sleep(300); } } if($radio == true) $radio = false; $dh->reply('4 Info Stream : OFF', $event->getName(), $dh->getCommandTrailing()); } ?> Hi there, First of all, I want to present the diagram that I'm working on. ----------- Diagram ----------- step2_a.php --| step2_b.php --|---> output.php step2_c.php --| (Process is included here) step2_d.php --| and here are the corresponding codes: step2_x: Code: [Select] . . . <form action="output.php" method="post" name="a"> req1: <input type="text" name="a_req_1"> req2: <input type="text" name="a_req_2"> . . . <input type="submit"> </form> ------ . . . <form action="output.php" method="post" name="b"> req1: <input type="text" name="b_req_1"> req2: <input type="text" name="b_req_2"> . . . <input type="submit"> </form> . . . . . . output.php: Code: [Select] <?php $form_name = $_POST['a']; if($form_name = "a") { //variables for a goes here //code goes here } elseif($form_name = "b") { //variables for b goes here //code goes here } elseif($form_name = "c") { //cariables for c goes here //code goes here } elseif($form_name = "d") { //variables for d goes here //code goes here } else { //code goes here } ?> Now, here's the problem. output.php always sees the primary condition as true. Even the data came from step2_b, the code does not recognize it. I tried to use "==" instead of "=" but the code sees the arguments as false so it executed the code on "else". How can I make the code distinguish the source of the data so that it would execute the right set of commands? Thanks in advance. Hoping to get some thoughts on how Doctrine array collections should be used when the position of the items in the collection must be controlled. For instance, I have a Chart object which has various primitive properties as well as a series property which is an array collection. Each member in the series collection is a Serie object which has various primitive properties as well as a data property which is an array collection. Each member in the data collection is a Datum object which includes various primitive properties. The following just refers to the series collection, however, will be doing the same with the data collection. Chart will have methods to add a Serie to the end of the series collection, modify a Serie for a given position, delete a Serie for a given position, swap the position of two Serie, and retrieve all Serie(s) in their designated position order. To implement this, my thought is to include a integer position property in Serie, and when retrieving the results will just ORDER BY this column if using DQL or maybe will use Criteria to filter the results. I am not, however, sure how to implement some of the other methods. When adding a new Serie to the end of the collection, should I do something like: class Chart { public function addSerie(array $params):Chart { $serie=new Serie(); $serie->setName($params['name']); $position=$this->series->count(); $serie->setPosition($position); $this->addSeries($serie); } }
class Chart { public function __construct() { $this->series->getIterator()->uasort(function ($first, $second) { return (int) $first->getPosition() > (int) $second->getPosition() ? 1 : -1; }); } }
PS. Originally, I was using the name "Series" instead of "Serie", but the lack of separate forms for singular and plural was messing with me. Was thinking of using SeriesNode instead, but didn't want to need to follow this same naming convention for other items... I think I am close, but not sure if I am quite there. Am I doing this correctly? I have several entity classes which will use class type inheritance:
MyNamespace\MyApp\Vehicle\Vehicle #MyNamespace.MyApp.Vehicle.Vehicle.dcm.yml MyNamespace\MyApp\Vehicle\Vehicle: type: entity table: vehicle_table inheritanceType: JOINED discriminatorColumn: name: discriminator_column type: string discriminatorMap: vehicle: Vehicle groundVehicle: MyNamespace\MyApp\Vehicle\GroundVehicle\GroundVehicle airVehicle: MyNamespace\MyApp\Vehicle\AirVehicle\AirVehicle repositoryClass: Vehicle id: id: type: integer generator: strategy: AUTO fields: grandParentItem1: type: string grandParentItem2: type: string #MyNamespace.MyApp.Vehicle.AirVehicle.AirVehicle.dcm.yml MyNamespace\MyApp\Vehicle\AirVehicle\AirVehicle: type: entity table: air_vehicle extends: MyNamespace\MyApp\Vehicle\Vehicle inheritanceType: JOINED discriminatorMap: airVehicle: AirVehicle airplane: MyNamespace\MyApp\Vehicle\AirVehicle\Airplane\Airplane rocket: MyNamespace\MyApp\Vehicle\AirVehicle\Rocket\Rocket repositoryClass: AirVehicle id: id: associationKey: true fields: parentItem1: type: string parentItem2: type: string #MyNamespace.MyApp.Vehicle.AirVehicle.Rocket.Rocket.dcm.yml MyNamespace\MyApp\Vehicle\AirVehicle\Rocket\Rocket: extends: MyNamespace\MyApp\Vehicle\AirVehicle\AirVehicle type: entity table: rocket_table id: id: associationKey: true repositoryClass: Rocket fields: childItem1: type: string childItem2: type: string I haven't shown GroundVehicle or Train, Car, and Airplane, but they are almost identical to AirVehicle and Rocket, respectively.
I've discovered that the barebone entities need to be manually created prior to using orm:generate-entities else I get class not found errors, and have created them as shown below. [michael@devserver doctrine]$ find inheritance_src -name "*.php" -exec cat {} \; <?php namespace MyNamespace\MyApp\Vehicle\AirVehicle\Airplane; class Airplane extends \MyNamespace\MyApp\Vehicle\AirVehicle\AirVehicle{} <?php namespace MyNamespace\MyApp\Vehicle\AirVehicle\Rocket; class Rocket extends \MyNamespace\MyApp\Vehicle\AirVehicle\AirVehicle{} <?php namespace MyNamespace\MyApp\Vehicle\AirVehicle; abstract class AirVehicle extends \MyNamespace\MyApp\Vehicle\Vehicle{} <?php namespace MyNamespace\MyApp\Vehicle\GroundVehicle\Car; class Car extends \MyNamespace\MyApp\Vehicle\GroundVehicle\GroundVehicle{} <?php namespace MyNamespace\MyApp\Vehicle\GroundVehicle\Train; class Train extends \MyNamespace\MyApp\Vehicle\GroundVehicle\GroundVehicle{} <?php namespace MyNamespace\MyApp\Vehicle\GroundVehicle; abstract class GroundVehicle extends \MyNamespace\MyApp\Vehicle\Vehicle{} <?php namespace MyNamespace\MyApp\Vehicle; abstract class Vehicle{} I then am able to successfully create the entities using orm:generate-entities, schema using orm:schema-tool:create, and repositories using orm:generate-repositories. Does everything seem correct? A couple of issues which I have my doubts: Locating the classes in inheritance_src/MyNamespace/MyApp instead of inheritance_src/MyApp. I tried to do the later and modify my psr-4 autoloader to use "MyNamespace\\": "inheritance_src/", but could not get it working without first creating the entities, editing them to add the "abstract" and "extend" portions, and then moving them to one directory lower. Needing to manually create the barebone classes in the first place. My meta-data definitions includes "extends: MyNamespace\MyApp\Vehicle\Vehicle", so I would thought it would not be necessary. Locate both the entities and repositories in the same folder. For that matter, I will probably be locating my service in the same folder as well. It seems that most frameworks will locate all the entities in one folder (with of course subdirectories), repositories in another, services in another, etc. The way I am doing seems to be organized domain modules as described by https://mnapoli.fr/organizing-code-into-domain-modules/. Any compelling reasons to do it one way or the other?
Thank you The following metadata... <?xml version="1.0" encoding="utf-8"?> <doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> <entity name="NotionCommotion\App\Account\PublicAccountIdIncrementor" table="public_account_id_incrementor"> <id name="account" association-key="true"/> <field name="chart_id" type="integer"> <options> <option name="default">0</option> </options> </field> <field name="source_id" type="integer"> <options> <option name="default">0</option> </options> </field> <one-to-one field="account" target-entity="NotionCommotion\App\Account\Account" fetch="LAZY" inversed-by="idPublicIncrementor"> <join-columns> <join-column name="id" referenced-column-name="id" nullable="false"/> </join-columns> </one-to-one> </entity> </doctrine-mapping> <?xml version="1.0" encoding="utf-8"?> <doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> <entity name="NotionCommotion\App\Account\Account" table="account"> <id name="id" type="integer"/> <one-to-one field="idPublicIncrementor" target-entity="NotionCommotion\App\Account\PublicAccountIdIncrementor" mapped-by="account"/> </entity> </doctrine-mapping> creates the following methods... <?php class Account { /** * Set idPublicIncrementor. * * @param \NotionCommotion\App\Account\PublicAccountIdIncrementor|null $idPublicIncrementor * * @return Account */ public function setIdPublicIncrementor(\NotionCommotion\App\Account\PublicAccountIdIncrementor $idPublicIncrementor = null) { $this->idPublicIncrementor = $idPublicIncrementor; return $this; } /** * Get idPublicIncrementor. * * @return \NotionCommotion\App\Account\PublicAccountIdIncrementor|null */ public function getIdPublicIncrementor() { return $this->idPublicIncrementor; } } As seen, Account::idPublicIncrementor allows NULL value. Is this by design since PublicAccountIdIncrementor's primary key is Account's primary key? If not, how do I instruct Doctrine to prevent NULL? This topic has been moved to Other Libraries and Frameworks. http://www.phpfreaks.com/forums/index.php?topic=324009.0 I am trying to class type inheritance with Doctrine. Eventually, I will be defining things using XML, but all the examples are done using doctags. I found the following and it seems to work. <?php use Doctrine\ORM\Mapping as ORM; /** * Inventory entity * * @ORM\Entity(repositoryClass="Inventory") * @ORM\Table(name="inventory") * @ORM\InheritanceType("JOINED") * @ORM\DiscriminatorColumn(name="discriminator_column", type="string") * @ORM\DiscriminatorMap({"inventory" = "AbstractItem", "inventory_room" = "Room"}) */ abstract class AbstractItem { /** * @ORM\Id @ORM\Column(name="inventory_id") @ORM\GeneratedValue * @var int */ protected $inventory_id; /** * @ORM\Column(type="string") * @var string */ protected $category; /** * @ORM\Column(type="string") * @var string */ protected $part_number; } use Doctrine\ORM\Mapping as ORM; /** * Inventory Room entity * @ORM\Entity * @ORM\Table(name="inventory_room") */ class Room extends AbstractItem { /** * @ORM\Column(type="string") * @var string */ protected $room_type; /** * @ORM\Column(type="string") * @var string */ protected $rack_limit;
But then I convert it to XML or YAML, and I get a Entity class 'Room' used in the discriminator map of class 'AbstractItem' does not exist error when trying to build the classes. I've also tried changing the type to mappedSuperclass, but no success. Any ideas? Also, what is the purpose of the DiscriminatorColumn? Thanks
AbstractItem: type: entity table: inventory inheritanceType: JOINED discriminatorColumn: name: discriminator_column type: string discriminatorMap: inventory: AbstractItem inventory_room: Room repositoryClass: Inventory id: inventory_id: type: string fields: category: type: string part_number: type: string Room: type: entity table: inventory_room fields: room_type: type: string rack_limit: type: string
<?xml version="1.0" encoding="utf-8"?> <doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> <entity repository-class="Inventory" name="AbstractItem" table="inventory" inheritance-type="JOINED"> <discriminator-column name="discriminator_column" type="string" length="255"/> <discriminator-map> <discriminator-mapping value="inventory" class="AbstractItem"/> <discriminator-mapping value="inventory_room" class="Room"/> </discriminator-map> <id name="inventory_id" type="string" column="inventory_id"> <generator strategy="IDENTITY"/> </id> <field name="category" type="string" column="category" precision="0" scale="0" nullable="false"/> <field name="part_number" type="string" column="part_number" precision="0" scale="0" nullable="false"/> </entity> </doctrine-mapping> <?xml version="1.0" encoding="utf-8"?> <doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> <entity name="Room" table="inventory_room"> <id name="inventory_id" type="string" column="inventory_id"> <generator strategy="IDENTITY"/> </id> <field name="room_type" type="string" column="room_type" precision="0" scale="0" nullable="false"/> <field name="rack_limit" type="string" column="rack_limit" precision="0" scale="0" nullable="false"/> <field name="category" type="string" column="category" precision="0" scale="0" nullable="false"/> <field name="part_number" type="string" column="part_number" precision="0" scale="0" nullable="false"/> </entity> </doctrine-mapping>
Anyone know why the following results in an error? Not a big deal as memory is not an issue and I can (and have) just changed it to create a new array instead of using a generator, but still curious. Thanks <?php foreach($doctrineCollection as $doctrineEntity){ yield new MyWrapper($doctrineEntity); /* After around 4 iterations, results in the following error: syslog Apr 06 15:25:25 myserver.net kernel: php-fpm[42889]: segfault at 7f8156a14100 ip 000055bb1d79acfd sp 00007ffd0b50a968 error 4 in php-fpm[55bb1d47c000+46e000] /var/log/php-fpm/error.log [Mon Apr 06 20:06:38.781360 2020] [proxy_fcgi:error] [pid 1501:tid 140210423629568] (104)Connection reset by peer: [client 12.345.67.890:45574] AH01075: Error dispatching request to : /var/log/httpd/error_log [06-Apr-2020 20:04:52] WARNING: [pool michael] child 5524 exited on signal 11 (SIGSEGV) after 0.138268 seconds from start [06-Apr-2020 20:04:52] NOTICE: [pool michael] child 5526 started */ } class MyWrapper { private $doctrineEntity; public function __construct($doctrineEntity) { $this->doctrineEntity=$doctrineEntity; } }
Finally getting around to giving Doctrine a try. Looks like YAML is depreciated, so my choices are DocBlocks or XML. I am sure it is personal choice, however, I would like to start off with what most feel is the best path. Any recommendations? Thanks I am currently using a single entity called id for a key. I'm now wanting to use two entities as a key - id and size. I've tried using these two peices of code, but failed: foreach ($_SESSION['cart']['content'] as $key=>$product,$size) { if ($product['id'] == $id && $product['size'] == $size) { $item_found = $key; break; } } // do thing ... and foreach ($_SESSION['cart']['content'] as $key=>$product && $key=>$size) { if ($product['id'] == $id && $product['size'] == $size) { $item_found = $key; break; } } // do thing Am I going the right way about it? Can two entities even be used as a key? For user content validation, I built my own custom class which is injected with an array which specified how the data will be validated and how to respond to the user if invalid data. It has a method to validate server side as well as a method to produce the jQuery validation plugin's client configuration JSON. The configuration array is defined by one or more JSON file located on the server. I am trying to determine where I should define which files should be used to validate data for a given entity. The easiest location is to store them directly in the entity in question, however, I have heard people voice that the entity shouldn't be responsible for validation. It isn't directly responsible how I am doing this, but would like to know whether there are any specific reasons why doing so might have undesirable consequences. Alternately, I can have them defined in the repository, however, it requires more logic. public function update(int $idPublic, array $params): Entity { $entity=$this->read($idPublic); //Option 1 $validationFiles=$entity->getValidatorFiles(); //Option 2 $repo=$this->em->getRepository(get_class($entity)); $validationFiles=$repo->getValidatorFiles(); $rules=$this->filesToArr($files); $validator=$this->validator($rules); //Closure will create new object $validator->validateNameValue($params); //Update entity and save return $entity; }
But where???
I have set up a script for people to remove themselves from a mailing list.
It worked fine so far, but when I added a possibility to show a message the entered email addres did not exist, things went wrong.
The script still runs, there are no errors, but when the user enters a non-existing email address, it still says "You have been removed".
Everything seemed to go well until I added a button to a URL (echo'd) rather than a plain link.
I have checked and rechecked, re-examined the flow, but I cannot find where I went wrong.
One further thing: the people get sent to this page by a one field form on a HTML page, with method "post".
Anyway, here is the script:
<HTML> <HEAD> <TITLE>Vlaanderen-Flanders</TITLE> </HEAD> <BODY> <?php // Always try to connect and select the DB before anything else $con = mysql_connect("localhost","jingleko_reload","*******") or die("Couldnt Connect to DB - ".mysql_error()); mysql_select_db("jingleko_reloader", $con) or die("Couldnt Select a DB - ".mysql_error()); // Set post var $Epost = trim(addslashes(strip_tags($_POST['Epost']))); // Look for it in DB $query = "SELECT Epost FROM newsletter WHERE Epost='".$Epost."'"; $result = mysql_query($query); //If found, do next thing if(isset($_POST['Epost'])) { mysql_query("DELETE FROM newsletter WHERE Epost='$Epost'") or die (mysql_error()); echo "<div align=\"center\"><img src=\"Pics/Vlaamse Leeuw.jpg\" width=\"114\" height=\"127\" border=\"0\"></div>"; echo "<p align=\"center\"><b>Thank you, you are now removed from the list.</b></p><br>"; echo "<p align=\"center\"><a href=\"index.htm\"><img src=\"Pics/begin.gif\" width=\"95\" height=\"30\" border=\"0\"></a></p>"; } else { echo "<div align=\"center\"><b><font color=\"red\">This address does not exist</font></b></div><br>"; echo "<div align=\"center\"><a href=\"eruit.htm\"><img src=\"Pics/herbegin.gif\" width=\"95\" height=\"30\" border=\"0\"></a>"; echo "<a href=\"index.htm\"><img src=\"Pics/begin.gif\" width=\"95\" height=\"30\" border=\"0\"></a></div>"; } mysql_close($con); ?> </BODY> </HTML>Any ideas, please? Sometimes when I altered the code, I just got a blank page. Thanks in advance. I'm tearing my hair out trying to work with "simple" XML for the first time. I'm building a small CMS for a Flash based site and the content is held in an XML file. My problem is that many of the copy fields are XML CDATA fields. On the one hand, with: $xml = simplexml_load_file($file, 'SimpleXMLElement', LIBXML_NOCDATA); I can pull the data out of that node and the CDATA tags are stripped. My issues come with trying to save the data with: file_put_contents($file, $xml->asXML()); Problems a a) tags are interpreted with their HTML entity equivalents. I don't want this to happen as it's a CDATA field being read by Flash. I gather this is coming from the asXML method because even if I do an html_entity_decode on the $_POST data it's still being converted. b) because of the above, there's no way to add the CDATA tags because they also have their charachters converted. SimpleXML so far has been anything but simple for me Has anyone ever run into this? Is there a way to save the file back in a way that will just keep my data exactly as is and also allow me to add the CDATA tags back in? the above/attached image shows a table outputted using a 'for loop', it has the action column that should either edit or delete entity... I need help to be able to edit or delete each entity by clicking the action link... find attached image... So I encode and decode html entities of my thread body variable in my script but now that I am working on the quote function I realize even after decode it prints the html entities instead of the regular character is there anyway to change this because if not it is going to print my font tag as characters instead of the font tag actually doing its job. Thanks! P.S. if this double posts I don't know what's going on...it happened last time but I didn't double post. It may be that I am using a mobile phone. |