PHP - Using Two Entities For A Key
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? Similar TutorialsFor 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; }
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. 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! 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'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... I am using PHP and Doctrine to store and manipulate Highchart objects such as the following: { "chart": { "type": "bar" }, "xAxis": { "categories": ["Africa", "America", "Asia", "Europe", "Oceania"] } }, "series": [{ "name": "Year 1800", "data": [107, 31, 635, 203, 2] }, { "name": "Year 1900", "data": [133, 156, 947, 408, 6] }, { "name": "Year 2000", "data": [814, 841, 3714, 727, 31] }, { "name": "Year 2016", "data": [1216, 1001, 4436, 738, 40] }] } My DB schema is: BarChart -id (PK) -name (string) BarChartSerie -id (PK) -barChartId (FK) -name (string) -position (int) BarChartCategory -id (PK) -barChartId (FK) -name (string) -position (int) BarChartNode -barChartSerie (FK) -barChartCategory (FK) -value (decimal) The chart entity has a collection of serie and category, and the serie and category entities both contain a reference to the shared node. I wish to clone the chart entity and thus use __clone() to set the chart, category, and serie entity's' PK to NULL, however, am running into issues as the node entity still has the original entitiy's PKs. I think maybe I should be creating the entities differently. Any suggestions how these objects should be created? Maybe instead have my series contain a collection of nodes and have each of these nodes contain a reference to the applicable category? 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; } }
Quotation marks are confusing me.
What do you guys use when it comes to quotation marks?
In HTML attributes and throughout the bodies of my web pages, I use the HTML entity ("). For example:
<a href="" title="Read "Article Name""> <p>In his new book, he says: "This is a quote."</p>I thought that this is the best practice. However, today, I read that it's perfectly safe to use straight quotes (") in the body, and that I should use the HTML entity only in HTML attributes. Is that correct? But what if I want to use curly quotes in the body instead of straight quotes? Should I always use the HTML entities for curly quotes (“ and ”), or can I also safely use the characters (“”)? I heard that straight quotes are safe in all browsers, even if you don't specify the character set of your web pages, but that curly quotes are only safe if you specify the character set or if you use the HTML entities. Is that true? And what about the <q> tag? Apparently, it's compatible with all browsers but they treat it differently. Edited by Fluoresce, 30 August 2014 - 07:37 AM. Hi Everybody. I hope someone here can advise the correct method for storing html/text in a MySQL DB AND retrieving it for updating via a <textarea> Basically, I need to store in my DB knowlege base articles, which have a title, category, product version/edition, description, solution, notes, etc... standard KB fields.. sorta... The issue I am experiencing, or the trouble I am having, is when I need to store both formatting HTML and output HTML in the solution or notes fields, html special chars are being interpreted and the HTML that should be displayed is not there. The char codes are interpreted and the browser then "hides" the HTML tags. For example, the solution may be this: Code: [Select] Find the following line: <serverURL>URL</serverURL> Change the URL to reflect your current server URL. The html chars are interpreted and changed to the actual less than and greater than signs rather than their &...; form (ie: < >   etc.) Some code snippets if it helps... Creating a record: Code: [Select] ... $sol = addslashes($_POST['asol']); $notes = addslashes($_POST['anotes']); include('./conf/connect.php'); mysql_query("INSERT INTO `faq_kb`.`articles` (`id`, `solution`, `notes`, `updated`) VALUES (NULL, '$sol', '$notes', NULL) ") or die(mysql_error()); mysql_close($conn); ... Retrieving a record: Code: [Select] ... include('./connect.php'); $get = $_GET['a']; $sql = "SELECT * FROM articles WHERE id='$get'"; $result = mysql_query($sql); mysql_close($conn); while($row=mysql_fetch_array($result)) { $solution = $row['solution']; $notes = $row['notes']; } ... <h4>Solution:</h4> <div align="right"><textarea name="rsol" style="width:550px;height:150px;"> <?php echo $solution; ?> </textarea></div> <h4>Notes:</h4> <div align="right"><textarea name="rnotes" style="width:550px;height:150px;"> <?php echo $notes; ?> </textarea></div> ... Updating a record: Code: [Select] ... $aid = $_POST['id']; $sol = addslashes($_POST['rsol']); $notes = addslashes($_POST['rnotes']); include('./conf/connect.php'); mysql_query("UPDATE `faq_kb`.`articles` SET solution='$sol', notes='$notes' WHERE id='$aid'") or die(mysql_error()); mysql_close($conn); ... I guess, you can ignore my whole spiel above and simply answer this question: what function do I need to use to encode the variable for inserting into the database, and what function do I then need to use to decode the variable for output so that it retains it's formatting html and my output/displayed html (< >)??? Thanks guys! I hope that this makes sense... ------------------------ Further Example: This is what is output (inside the dashes): ---------------------------- To configure your SysAid Server logging to debug mode please do the following. Open the file serverConf.xml located in the directory: [...\SysAidServer\root\WEB-INF\conf\] Change <sysaidLogLevel>info</sysaidLogLevel> to <sysaidLogLevel>debug</sysaidLogLevel> Save the change and then restart the SysAid Server service. -------------------------- And this is what the source of that looks like: Code: [Select] <div class="divText" id="txtselect"><p> <span style="font-size: 10pt; font-family: 'Times New Roman',serif; color: black;" lang="EN-US"> To configure your SysAid Server logging to debug mode please do the following.</span></p> <p><font size="2"><span style="font-family: 'Times New Roman',serif;">Open the file </span></font> <span style="font-size: 10pt; font-family: 'Times New Roman',serif; color: black; font-style: italic;" lang="EN-US"> serverConf.xml</span><span style="font-size: 10pt; font-family: 'Times New Roman',serif; color: black;" lang="EN-US"> located in the directory:</span></p> <p><font size="2"><span style="font-family: 'Times New Roman',serif;"> </span></font> <span style="font-size: 10pt; font-family: 'Times New Roman',serif; color: black;" lang="EN-US"> [...\SysAidServer\root\WEB-INF\conf\] </span></p> <p> <span style="font-size: 10pt; font-family: 'Times New Roman',serif; color: black;" lang="EN-US"> Change <br> </span><font face="Courier New"> <span style="font-size: 10pt; color: black;" lang="EN-US"> <sysaidLogLevel>info</sysaidLogLevel><br> </span></font> <span style="font-size: 10pt; font-family: 'Times New Roman',serif; color: black;" lang="EN-US"> to<br> </span><font face="Courier New"> <span style="font-size: 10pt; color: black;" lang="EN-US"> <sysaidLogLevel>debug</sysaidLogLevel></span></font></p> <p><span style="font-size: 10pt; color: black;" lang="EN-US">Save the change and then restart the SysAid Server service.</span></p> </div> And this is a copy paste straight out of phpMyAdmin: Code: [Select] <p> <span lang="EN-US" style="font-size: 10.0pt; font-family: 'Times New Roman',serif; color: black"> To configure your SysAid Server logging to debug mode please do the following.</span></p> <p><font size="2"><span style="font-family: 'Times New Roman',serif">Open the file </span></font> <span lang="EN-US" style="font-size: 10.0pt; font-family: 'Times New Roman',serif; color: black; font-style: italic"> serverConf.xml</span><span lang="EN-US" style="font-size: 10.0pt; font-family: 'Times New Roman',serif; color: black"> located in the directory:</span></p> <p><font size="2"><span style="font-family: 'Times New Roman',serif"> </span></font> <span lang="EN-US" style="font-size: 10.0pt; font-family: 'Times New Roman',serif; color: black"> [...\SysAidServer\root\WEB-INF\conf\] </span></p> <p> <span lang="EN-US" style="font-size: 10.0pt; font-family: 'Times New Roman',serif; color: black"> Change <br> </span><font face="Courier New"> <span lang="EN-US" style="font-size: 10.0pt; color: black"> <sysaidLogLevel>info</sysaidLogLevel><br> </span></font> <span lang="EN-US" style="font-size: 10.0pt; font-family: 'Times New Roman',serif; color: black"> to<br> </span><font face="Courier New"> <span lang="EN-US" style="font-size: 10.0pt; color: black"> <sysaidLogLevel>debug</sysaidLogLevel></span></font></p> <p><span lang="EN-US" style="font-size: 10.0pt; color: black">Save the change and then restart the SysAid Server service.</span></p> Then EVEN CRAZIER, I click the edit button on the article and this is (direct copy paste) what is output to the <textarea>: Code: [Select] <p> <span lang="EN-US" style="font-size: 10.0pt; font-family: 'Times New Roman',serif; color: black"> To configure your SysAid Server logging to debug mode please do the following.</span></p> <p><font size="2"><span style="font-family: 'Times New Roman',serif">Open the file </span></font> <span lang="EN-US" style="font-size: 10.0pt; font-family: 'Times New Roman',serif; color: black; font-style: italic"> serverConf.xml</span><span lang="EN-US" style="font-size: 10.0pt; font-family: 'Times New Roman',serif; color: black"> located in the directory:</span></p> <p><font size="2"><span style="font-family: 'Times New Roman',serif"> </span></font> <span lang="EN-US" style="font-size: 10.0pt; font-family: 'Times New Roman',serif; color: black"> [...\SysAidServer\root\WEB-INF\conf\] </span></p> <p> <span lang="EN-US" style="font-size: 10.0pt; font-family: 'Times New Roman',serif; color: black"> Change <br> </span><font face="Courier New"> <span lang="EN-US" style="font-size: 10.0pt; color: black"> <sysaidLogLevel>info</sysaidLogLevel><br> </span></font> <span lang="EN-US" style="font-size: 10.0pt; font-family: 'Times New Roman',serif; color: black"> to<br> </span><font face="Courier New"> <span lang="EN-US" style="font-size: 10.0pt; color: black"> <sysaidLogLevel>debug</sysaidLogLevel></span></font></p> <p><span lang="EN-US" style="font-size: 10.0pt; color: black">Save the change and then restart the SysAid Server service.</span></p> Notice how there are NO < or > chars in this? How do I make this work Thanks guys |