PHP - Prevent Null In One-to-one Doctrine Relationship
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? Similar TutorialsI have a table for logins and a table for addresses. I'm using 1 form to create the username/password (which is being inserted into the "logins" database), and the persons name, address, etc. which is being inserted into the "addresses" database. What do I need to do to make it so that when a user log's in to the site and make's it to the checkout page, that their address is tied to their username? Ok, something I haven't done yet, I've programmed the majority of my site so far and have yet needed to utilize my relationships. Hopefully I set the tables up correct with foreign keys, primary keys, constraints, and references. This is what I need to do, should be relatively easy for most people here. I have one table... Friends with columns... friend_id - id of the friend users_id - id of the user who added the friend I have another table Statuses with columns... users_id - id of the user who posted the status statuses - the status posted whens - the time the status posted ------ I have statuses properly posting to a person's profile.php page but, I want the homepage of the site (same concept as Facebook) to post the status of your friends. I mean, what's the purpose of a status if your friends can't see them. ------ So, I need to somehow extract all of a users friends from the friends table, and use those friends to insert the statuses of friends on someone's homepage. Much help is greatly appreciated. If you wish to see how my tables are set up and if they are correct, that would be appreciated, just ask, and I'll go get my sql query of those tables for you to look at. THANKS! By the way, my site is at... http://inyoursocialnetwork.netne.net - the domain name and the site name are just temporary fill ins. If you have any ideas or suggestions for a good name, please, please, please let me know. It's driving me nuts I can't come up with a good name. I would prefer a short one. Shorter is easier to type and generally easier to remember. Hi, I am re-visiting my database table relationship for criminal incidents. Six tables are involved plus a junction table to make it seven tables in total. I need someone to review this relationship and advise whether or not it is correctly set up. The relationships are as follows: 1. A person can belong to more than one incident: t_persons (one-to-many) t)_incidents_persons 2. A person can only have one nationality by birth t_persons (one-to-one) t_countries 3. An agency can have more than one incident t_agencies (one-to-many) t_incidents 4. A status (e.g. closed incident) can belong to more than one incident t_status (one-to-many_ t_incidents 5. A keyword (i.e. offence type eg theft) t_offencekeywords (one-to-many) t_incidents Hi all I have 3 tables Table_1, Table_2 and Table_3 Table_1 is a list of countries, with name and country_id Table_2 is a table that has 3 fields, id, name and description Table 3 is a table that has name, Table_2_id So what I need to do: Display the name and description field of Table_2 in a form Loop through the countries table and display each as an input box and display on the same form When I fill out the form details, the name/description must be inserted into Table_2, creating an id The input boxes data then also needs inserting into Table_3, with the foreign key of Table_2_id So a small example would be: Name: testing Description: this is a test Country of Australia: Hello Country of Zimbabwe: Welcome This means that in Table_2, I will have the following: ============================= | id | name | description | 1 | testing | this is a test ============================= Table_3 ============================= | Table_2_id | name | country_id | 1 | Hello | 20 | 1 | Welcome | 17 ============================= 20 is the country_id of Australia 17 is the country_id of Zimbabwe Code: Generating the input fields dynamically: $site_id = $this->settings['site_id']; $options = ''; $country_code = ''; $query = $DB->query("SELECT country_code, country_id, IF(country_code = '".$country_code."', '', '') AS sel FROM Table_1 WHERE site_id='".$this->settings['site_id']."' ORDER BY country_name ASC"); foreach ($query->result as $row) { $options .= '<label>' . 'Test for ' . $this->settings['countries'][$row['country_code']] . '</label>' . '<br />'; //$row['country_id'] is the country_id from Table_1 $options .= '<input style="width: 100%; height: 5%;" id="country_data" type="text" name="' . $row['country_id'] . '" value="GET_VALUE_FROM_DB" />' . '<br /><br />'; } echo $options; This outputs: Code: [Select] Textareas go here...... <label>Test for Australia</label> <input type="text" value="" name="20" id="country_data" style="width: 100%; height: 5%;"> <label>Test for Zimbabwe</label> <input type="text" value="" name="17" id="country_data" style="width: 100%; height: 5%;"> Now, I need to insert the value of the input field and it's country_id (20 or 17) into Table_3 and also Table_2_id. This then means I could get the value from Table_3 to populate 'GET_VALUE_FROM_DB' But I'm at a loss on how I'd do this. Could someone help me with this? Thanks Hi,
I want each new incident created into the t_incidents table by the user to be associated with the AgencyID, a foreign key in the t_users table.
The problem is I do not know how this relationship will work and whether I will need a junction table.
The two tables a
t_Users +----------+----------+------------+ |UserID | AgencyID |User name | +----------+----------+------------+ |1 | 1 |john | +----------+----------+------------+ |2 | 1 |andrew | +----------+----------+------------+ t_Agencies +----------+------------+ |AgencyID |agency name | +----------+------------+ |1 |police | +----------+------------+ |2 |immigration | +----------+------------+I will appreciate your advice. Joseph Edited by josephbupe, 13 October 2014 - 03:04 AM. I am trying to update the database with isset to set the value of the variable to either null or the value entered by the user. Currently, if no value has been entered null is being set as a string causing the date field to populate with zeros. How do I code it so that it populates or sets the value as null and not as string null?
Here's my code: (yes I know sql injections it's still in development )
<?php 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 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... 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>
I'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! 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 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; } }
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; } }
I am a little confused with the difference between Symfony Events and Event Listners and Doctrine Events. The Doctrine events look pretty straight forward and are primary used for entity persistence, and I have outlined my understanding below: Doctrine Lifecycle Callbacks. Single entity and single Doctrine event. Method in class. Good performance. Don't have access to Symfony services (all others do) Doctrine Lifecycle Listeners. All entities and single Doctrine event. Separate class and configured in config.service.yaml. Doctrine Entity Listeners. Single entities and single Doctrine event. Separate class and configured in config.service.yaml. Doctrine Lifecycle Subscribers. All entities and multiple Doctrine event. Must implement EventSubscriber (or probably EventSubscriberInterface) Separate class and configured in config.service.yaml.I am more confused with the Symfony events and my interpretation as listed below is likely incorrect. Symfony Event Listeners. Single Symfony event. Separate class and configured in config.service.yaml. More flexible because bundles can enable or disable each of them conditionally depending on some configuration value. Symfony Event Subscribers. All specified Symfony events. Must implement EventSubscriberInterface Separate class but NOT configured in config.service.yaml but in class. Easier to reuse because the knowledge of the events is kept in the class rather than in the service definition.Are they used for totally different purposes or can one use Symfony events to also deal with entities? Where would one want to use these Symfony events? Is there a reason why Doctrine Lifecycle Subscribers are located in src/EventListener and not src/EventSubscriber Are Doctrine Lifecycle and Entity Listeners really only for a single event as I interpret the documentation states, or is it one method per Doctrine event such as the following? App\EventListener\SearchIndexer: tags: - name: 'doctrine.event_listener' event: 'postPersist' - name: 'doctrine.event_listener' event: 'postUpdate'
Hello Guys, Iam making a new ad serving script. In that site every publisher can register & they will get a url to serve ads. When a user click on that url the publisher will get earnings. But my problem is someone using something like this <iframe src="http://my-site.com/adserve.php" width = "100" height = "100"></iframe> & it will helps to get earnings without clicking on that url. I want to prevent this type of cheating & how it can be possible ?? I hope a expert will replay for me. Will this prevent a SQL injection? I am guessing the answer is no because it is too simple. // retrieve form data ========================================== $ama = $_POST['ama']; // Check for alphanumeric characters ===================================== $string = "$ama"; $new_string = preg_replace("/[^a-zA-Z0-9\s]/", "", $string); // echo $new_string; // Send query =========================================================== $query = "SELECT * FROM members WHERE ama='$new_string'"; if (!mysql_query($query)){ die('Error :' .mysql_error()); } I am loading a link with ajax. When the link pops on the screen and I click it, I get redirected to my 404 page and my lightbox doesn't load. If the link pops in and I refresh my browser, then I click the link my lightbox will show up. How can I do a prevent default on the <a href> in pure JS? No frameworks please. Based on the comments on my previous question, took some tutorials on how to avoid injections on query. Does the code below prevents against it in any way.? Secondly, can you recommend a good article that writes well in how to secure input data by users. Please be kind with your comments.😉😉. Thankks in advance.
The code works fine. <?php include 'db.php'; error_reporting(E_ALL | E_WARNING | E_NOTICE); ini_set('display_errors', TRUE); if(isset($_POST['submit'])) { $username = $_POST['username']; $password = ($_POST['password']); $sql = "SELECT * FROM customer WHERE username = ?"; $stmt = $connection->prepare($sql); $stmt->bind_param('s', $username); $stmt->execute(); $result = $stmt->get_result(); $count = $result->num_rows; if($count == 1) { while ($row = $result->fetch_assoc()) { if ($row['status'] == 'blocked') { echo'your account is suspended' session_destroy(); exit(); } else if($row['status'] == 'active') { if($username !== $row['username']) { echo '<script>swal.fire("ERROR!!", " Username is not correct. Check Again", "error");</script>'; } if($password !== $row['password']) { echo'<script>swal.fire("ERROR!!!", "Your Password is Incorrect. Check Again.", "error");</script>'; } if($username == $row['username'] && $password == $row['password']) { header('Location:cpanel/'); else { } }//if count }//while loop }//submit ?>
|