I have three different types of XML files (structure) which I would like to import into a database.
Every hour a cronjob calls my import.php with a specific XML file type as a parameter.
The import script includes a bootstrap.php (AutoLoader, Setup Doctrine DB Connection) and puts all files matching the name convention of this type in an array and calls a static method for this class.
Simplified code (import.php):
<?php
require_once("bootstrap.php");
function getFiles($pattern)
{
$fileList = NULL;
foreach( glob('xml/*'.$pattern.'.xml') as $filename )
{
$fileList[] = $filename;
}
return $fileList;
}
switch($xmlType)
{
case "TypeA":
TypeA::importFeed(getFiles($xmlType));
break;
case "TypeB":
TypeB::importFeed(getFiles($xmlType));
break;
case "TypeC":
TypeC::importFeed(getFiles($xmlType));
break;
}
Currently, the classes (TypeA
, TypeB
, TypeC
) contain no other method except importFeed
.
Inside importFeed
, only 2 things are equal in each class:
- Getting the
entityManager
(Doctrine) by calling$em = app::getEm();
- Convert XML into
SimpleXMLElement
using my parser class$feedObj = Parser::xmlToObject($xmlFile);
Everything else in importFeed
differs from class to class because of the different XML types. Only a few tasks repeating e.g. check if an entity already exists in the database.
My first thought was creating a Helper class for this and some other repeating tasks I also need outside the import-script in this application.
But I'm not sure if this helper class should be a normal, "static" or "singleton" class.
The helper-methods doesn't need a specific object instance so static-methods would a good choice. But in some methods I need access to the DB and I do not wont to call app::getEm();
in every method because I don't think this is a good/clean solution.
At this point I challenged my current application design and read a lot of articles about this. The point is the application is not large and it should not be so using a Framework like Symfony is completely exaggerated - nonetheless I want a good solution.
All three classes (TypeA/B/C) have the same function that looks like this:
public static function importFeed($xmlFiles)
{
$em = \App::getEm();
foreach($xmlFiles as $xmlFile)
{
try
{
$feedObj = Parser::xmlToObject($xmlFile);
...import xml data to database - differns ...
}
catch(\Exception $e)
{
....
}
}
}
Only the "..." area differs a lot because of the different XML structure but this part isn't really important for the question. In short: A Doctrine entity is created and many setAttributeX
methods are called and in the end $em->flush()
.
My feeling tells me that it is not right to have three classes with only static methods to import XML files, but I can't find a better solution.