PHP - Alternatives To Entity Inheritance
I am using API-Platform, Doctrine, and Symfony with entities that utilize class type inheritance to extend an abstract entity. I've been running into one issue after another primarily related to the serialization process (serialization groups, parent annotations not propagated to the child, etc), and while I am sure user error on my part is part of the culprit, it appears that API-Platform and potentially Symfony and Doctrine don't fully support entity inheritance. My reason for thinking so is the incredibly sparse amount of documentation on the subject and remarks on quite a few github issues posts and other blogs how it is "bad practice". For instance, say I have Mouse, Cat, and Dog which all extend AbstractAnimal, and each has a bunch of common properties such as birthday, weight, etc, and methods such as eats(), sleeps(), etc. Sorry in advance for using hypothetical entities but I don't think doing so distracts. I like how inheritance allows me to keep all common properties in a single table, but can let that go. More importantly, the subset mouse, cat, and dog table shares an ID from the animal table allowing me to associate all animals to some other table (i.e. many-to-one to person whether they are their pet or many-to-many to country whether they are native to a country), and to retrieve a list of animals and filter by some property or type as needed without a bunch of unions. To me, this sounds like inheritance, but if the products I am using don't support it very well, it doesn't matter. First question. Is entity inheritance considered bad practice? And even if not, is it common for frameworks to limit their level of support for them? If so, what can I do about it? Maybe favor composition over inheritance? Okay, great, I now have a single animal table which makes all my SQL concerns issues go away and I am pretty confident that my serialization issues will also go away. All I need to do is inject each animal with some "thing" to make them a mouse, cat, or dog. But what do I call this thing? I've struggled with this topic for a while and asked the same question regarding how to deal with BarCharts, PieCharts, GaugeCharts, LineCharts, etc all being charts but all acting slightly differently, and never really came to any conclusion. For a non-hypothetical scenario, I have BacnetGateway and ModbusGateway which extend AbstractGateway. Okay, this one is easy and I change to just having a Gateway and inject either BacnetProtocol or ModbusProtocol. For another non-hypothetical scenario, I have PhysicalPoint which represents some real environmental parameter, VirtualPoint which represents combining one or more PhysicalPoints or VirtualPoints, and TransformedPoint (feel free to provide a better name) which represents performing some time function such as integrating over a given time. Currently, they all extend AbstractPoint, but if I was trying to do so with composition, I could inject PointType but don't think doing so makes sense. For my hypothetical scenario, do I make a DNA interface and inject an Animal with DogDNA to get a dog? I really need to get my head around this once and for all. Thanks Similar TutorialsI can create a one-to-one relationship between two tables by placing a unique constraint on the foreign key and making it NOT NULL, and make it one-to-at-most-one by removing the NOT NULL constraint. My question is what criteria should one use to determine which table holds the foreign key? For instance, I have the Car and Motor entities as shown below where one Car has one Motor, and conversely one Motor is used by one Car.
AbstractPart
Car extends AbstractPart What reasoning should one use to determine whether the Car table contain the Motor ID or should the Motor table contain the Car ID? Is there a way to make it
How can I go about removing a $_SESSION entity if certain array values of it equal a specific value? I am thinking something along the lines of this: if (isset($_SESSION['cart']['content'][$_POST['id']])) = array ('sizes' => 0, 'sizem' => 0, 'sizel' => 0, 'sizexl' => 0) { // remove $_SESSION['cart']['content'][$_POST['id']] } Hello I am working on my graduation project and I have a critical problem with my php code and I am just beginner in php coding. I am reading from text file IDs of papers and want to link between the ID that I read form my text file and the XML file so that is my code : <?php $file = fopen("abstract/Temp_id.txt","r"); $ids; while(!feof($file)) { $ids = fgets($file); $xml = simplexml_load_file("abstract/$ids");//abstract is the folder which I save my files and //read from it $title="bibliomisc =".$xml->articleinfo[0]->bibliomisc; echo $title; echo"<a href=abstract/$ids title='Click to open '>$ids</a>"; } fclose($file); ?> BUT I worked on openssl and it is working if I give it the name of ID e.g. $xml = simplexml_load_file("abstract/8104317");//it is working but if I read from file I got that error Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "8104317.xml " in /opt/lampp/htdocs/GP/xml_test.php on line 9 Notice: Trying to get property of non-object in /opt/lampp/htdocs/GP/xml_test.php on line 12 Notice: Trying to get property of non-object in /opt/lampp/htdocs/GP/xml_test.php on line 12 bibliomisc = 8104317.xml Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "" in /opt/lampp/htdocs/GP/xml_test.php on line 9 Notice: Trying to get property of non-object in /opt/lampp/htdocs/GP/xml_test.php on line 12 Notice: Trying to get property of non-object in /opt/lampp/htdocs/GP/xml_test.php on line 12 bibliomisc = help please thanks 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 a little experienced with PHP sessions, but not totally as I haven't got my head completely around its logic yet, as your about to see. I wonder wondering how I can go about adding a session entity from a HTML form input? I'm guessing it will be something like: $_POST['name'] => $_SESSION['delivery']['name']; Then, to echo the session entity, you would simply do something like: echo $_SESSION['delivery']['name']; ? I have: {$content['size']} inside Code: [Select] echo ""; I had to switch the quotes around because I added something else that required me to do so, so it now sits at this: {$content["size"]} inside Code: [Select] echo ''; Before I made the quote switch, it was echoing "Large", which is correct. Now after the switch, it echo's "{$content["id"]} ". Why?! I've tried 567568758654 different combinations of quotes and removing {} and stuff but non of them fix it. I don't even see why its suddenly not even echoing! All I did was quote reverse! I'm wondering if there's any alternatives to redirecting. For example, after the registration process, I have a fully loaded User object with all of the information I need to load the user's profile (the place that logging in/registering takes you to). I can call the profile action of the user controller and pass in the User object and it will display just fine. The problem is that since the URL is still pointing to the register action if the user refreshes their page its going to try sending the previous form again. Alternatively I could redirect to the profile and have it load that way, but then I'm fetching data from the database seemingly unnecessarily since I had all of the data I needed already fetched prior to redirecting. Is there anyway that I could do the first process but change the url and forget the previous form data so that if they refresh its just refreshing the profile and not resending the previous request? Thanks in advance for any help. I created had created a website between me and a couple friends. On the website I made an Ajax\Javascript\Php Instant Messenger. It works fine for something small. Each user has a contact list and currently I am saving each individual conversation between each user into an Sql table { senderId, RecieverId, Message } and reading it back. Now I know its no problem for something small but obviously it leaves security risks and sends too many requests to the server. Any of you guys have any alternative Idea's for this messenger? I don't necessary need to save the conversations, I'm simply using that method to send and receive them. I have a buddy who does his messenger through J.S sockets but I would like to keep to php if possible. Any comments or suggestions would be much appreciated. Uploaded with ImageShack.us Sometimes I have various data which I wish to be available to all scripts. Typically, they are constants which are related, and using PHP's constants makes them difficult to group.
As such, my solution has been to create a single global variable such as $GLOBALS['myGlobalVariable'], and dump them all in it.
Are there better ways to implement this? For instance, using a singleton? Please provide rational why one solution is better than the other.
Thank you
<?php class mySinglton { private static $instance = NULL; private function __construct() {} private function __clone(){} public static function mySinglton($values=null) { if (!self::$instance) { self::$instance = new stdClass(); foreach ($values as $key=>$value) { self::$instance->$key=$value; } } return self::$instance; } } class someClass { public $a=1,$b=2,$c=3; } $globals=array( 'foo'=>'bar', 'daysOfWeek'=>array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'), 'someClass'=>new someClass ); $GLOBALS['myGlobalVariable']=$globals; mySinglton::mySinglton($globals); testIt(); function testIt() { echo('<pre>'.print_r($GLOBALS['myGlobalVariable'],1).'</pre>'); echo('<pre>'.print_r($GLOBALS['myGlobalVariable']['foo'],1).'</pre>'); echo('<pre>'.print_r(mySinglton::mySinglton(),1).'</pre>'); echo('<pre>'.print_r(mySinglton::mySinglton()->foo,1).'</pre>'); } ?> If I want to load some user information from the database into an object/array and share it throughout my application, what's the best approach for this? Here is what I thought of doing: - I can call a function (e.g user_info() ) that will return the user information whenever I need it , but It'll have to run a DB query each time I call it. - Load user information once from the DB, assign it into a global array/object, then call that object whenever I need it. A lot of people recommended against using global variables, but I think performance wise it's better than running a query each time. Are there any better alternatives than the above approaches? Hello again, So, after messing around with gettext, and having found the solution to my previous post (https://forums.phpfreaks.com/topic/310383-gettext-for-multilangual-not-working-for-me/), I've come to the conclusion that I need to use something else than gettext in order to make my site multilingual.
Problem I have with gettext is that I absolutely need to have my desired languages (i.e. fr_FR, nl_NL, etc) installed on my server's system (in my case, a NAS for now). I can see which locales I have on my server with 'locale -a'. I am in no way able to install new locales on my NAS. It's too limited... too much locked down. So, I'm looking for an alternative to gettext. Any suggestions for me perhaps ? Thanks for any advice. Pat
I am trying to do the following. Except I know that 'return' is not the right method to use, as it stops the script, so what ends up happening is only one row is returned, instead of the three that are there. With return, the data is being passed without being immediately printed, and I end up with the data (but not all of it, because the script stops) in correct place in the page. If I replace return () with echo(), it works fine, in terms of returning the correct data. However, with the way things are setup, if I use echo, the results print at the head of my page. I am using function CreateSideMenu to establish the values for content, and then another function, later on the index.php page, actually creates the page. So what I need is to have something, similar to return (), that passes the information on, but does not immediately print it. Do I make sense? see code below: function CreateSideMenu () { // open CreateSideMenu function include ('/Users/max/Sites/rdbase-llc/hidden/defin/kinnect01.php'); $query = "SELECT content_element_title, content_element_short_text FROM content_main"; $result = mysql_query ($query, $dbc); while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) { return ("<p>" . $row[content_element_title] . "</h2>\n<p>" . $row[content_element_short_text] . "</p>"); } Thanks ahead of time. Now i use a very complex normal for, how i can use a foreach? This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=326703.0 I was looking over some code that someone else had written when I noticed a line with "$this->entity" in it. "Entity" is recognized as PHP syntax in my text editor but I cannot find any reference to it in any documentation that I've looked through. Where can I find more information about the "entity" class? Thanks in advanced! I have
class MyProductClass { function computeProductA() { doSometing(); } function computeProductB() { doSometingElse(); $this->computeProductCommon(); } function computeProductC() { $this->computeProductCommon(); } function computeProductCommon() { } }And I was wondering ... does it make sense to move out product-specific functions into their own classes and then have them extend MyProductClass. While I think it makes sense to me from an aesthetic point of view, and that I get to use object oriented principles, I could not answer myself as to "Why" I would do that. So, why? Why would I do that, and should I? Right now in the code, various product specific classes instantiate MyProductClass and just use their specific and generic functions, as needed. Edited by dennis-fedco, 15 December 2014 - 09:55 AM. Context. Class AbstractTenantEntity's purpose is to restrict access to data to the tenant (i.e. account, owner, etc) that owns the data. Any entity which extends it will have the TenantId added when created and the TenantId in the WHERE clause for all other requests. Tenant typically does not have collections of the various entities which extend AbstractTenantEntity, but does for a few of them do. When using annotation, I handled it by applying Doctrine's AssociationOverride annotation to the extended classes which should have a collection in Tenant. use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity() */ class Tenant { /** * @ORM\OneToMany(targetEntity=Asset::class, mappedBy="tenant") */ private $assets; // Other properties and typical getters and setters }
use Doctrine\ORM\Mapping as ORM; abstract class AbstractTenantEntity implements TenantInterface { /** * inversedBy performed in child where required * @ORM\ManyToOne(targetEntity=Tenant::class) * @ORM\JoinColumn(nullable=false) */ protected ?Tenant $tenant = null; // Typical getters and setters }
use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity() * @ORM\AssociationOverrides({ * @ORM\AssociationOverride(name="tenant", inversedBy="assets") * }) */ class Asset extends PublicIdTenantEntity { // Various properties and typical getters and setters }
So, now I am changing from annotations to attributes, and modified AbstractTenantEntity as follows: use Doctrine\ORM\Mapping\ManyToOne; use Doctrine\ORM\Mapping\JoinColumn; abstract class AbstractTenantEntity implements TenantInterface { /** * inversedBy performed in child where required */ #[ManyToOne(targetEntity: Tenant::class)] #[JoinColumn(nullable: false)] protected ?Tenant $tenant = null; // Typical getters and setters } Next I went to modify Asset and realized that there didn't appear to be an attribute for AssociationOverride. I found a little discussion on the topic on github but couldn't find any resolution. Question Can inheritance be used with PHP 8 attributes where the property is defined in the parent class and the attribute is applied in the child class? Googling php 8 attributes inheritance didn't provide anything and thus I expect the answer is no but thought I'd ask. Thanks
EDIT. Maybe Doctrine does have an attribute version: https://github.com/doctrine/orm/blob/2.9.x/lib/Doctrine/ORM/Mapping/AttributeOverride.php EDIT2. Actually don't think so Edited July 30 by NotionCommotionHello, I have two classes: Code: [Select] abstract class Serializable { public function serialize() { foreach($this as $member => $value) { $publicObject->$member = $value; } return $publicObject } } class ToSerialize extends Serializable { public function otherSerialize() { foreach($this as $member => $value) { $publicObject->$member = $value; } return $publicObject } } $foo = new ToSerialize(); $foo->serialize(); //This will return one thing $foo->otherSerialize(); //This will return something different Why does this happen? Hey again, I hope you guys don't get annoyed with my noob questions. I was reading the guide here on the site about OOP, and on the section related to inheritance it makes a "Dog" class, after giving it an attribute and a method it then creates the "Animal" class using "extends" and expands on the methods. Then after that here is the paragraph I'm looking at now. "Class Animal is unaware of the fact that it is being extended; there are no references to Dog whatsoever. Say Animal extended another class called LifeForm, and I instantiated Animal, only methods and properties of Animal and LifeForm would be included in the object." To me, this sounds like if I were to create this "LifeForm" class by further extending the "Animal" class, I would not be able to access any of the attributes and methods that were in "Dog," only the ones that were in Animal and any that I put in LifeForm itself. But, I was playing with the code and I can call an attribute from Dog in LifeForm. So, am I reading the post wrong or am I coding wrong? Code: (php) [Select] <?php //Class Dog// class Dog{ public $hungry = 'Hell yeah!'; public $test = 'Affirmative!'; function eat($food){ $this->hungry = 'not so much.'; } } //Class Animal// class Animal extends Dog{ function eat($food){ if($food === 'cookie'){ $this->hungry = 'not so much'; }else{ echo 'Barf! I only like cookies!'; } } } //Class LifeForm// class LifeForm extends Animal{ function eat($food){ } } //Program Variables// $dog = new Dog; $LifeForm = new LifeForm; //Program Code// echo $LifeForm->test; ?> My assumption was that I am able to call that attribute because of the 'public' in front of it, but all the attributes in the examples are also public. Thanks guys! Hi, After a long time I start php again to do some stuff and using OOP concept for the first time and getting this below error Code: [Select] PHP Fatal error: Class 'SystemConfig' not found in /home/tanveer/Workspace/EmailTest/webapp/classes/MailParser.class.php on line 12, referer: http://localhost/EmailTest/public_html/index.php My project directory structure is as follows: Code: [Select] \webapp: |- classes |- MailParser.class.php |-DatabaseConnect.class.php |-SystemConfig.class.php \public_html: |-header.php |-footer.php |-gencsv.php |-stat.php \css |-style.css \images index.php And the php code file that I am trying to make work is as follows: class MailParser extends SystemConfig { /* Reads the files passed line-by-line * @param $fileName */ public function readFiles($fileName){ $fileHandler = fopen($fileName,'r'); while ($line = fgets($fileHandler)) { echo $line."<br />"; } fclose($fileHandler); } /* Traverse the user specified directory * @param $dirPath */ public function traverseDirectory($dirPath) { echo $dirPath; $sentFolderPath = new SystemConfig(); $sentFolderPath->getSentMailFolder(); $totalDirPath = $dirPath."/".$sentFolderPath; echo $totalDirPath; $io=0; if ($handle = @opendir($dirPath)) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $newdir = ""; $filetext = ""; if (!is_file($dirPath."/".$file) or is_dir($dirPath) ) { $io++; $newdir.= $dirPath."/".$file."/"; print $newdir."<br />"; $this->traverseDirectory($newdir); if(is_file($dirPath.$file)) { $text = str_replace('//','/',"".$dirPath.$file."\n"); } } } } closedir($handle); } } } $rmf = new MailParser(); $rmf->traverseDirectory($_POST["dirpath"]); ?> |