帮助创建一个可重用的 PHP 函数,该函数将“动态”地运行。调用其他函数

发布于 2024-08-17 19:31:47 字数 3700 浏览 2 评论 0原文

这是我第一次尝试认真使用 MySQL 中的关系数据库以及使用 CodeIgniter 在 PHP 中创建的某种 CMS。
我来到了必须在几个多对多相关表中插入一些数据的部分。
在我的代码中,一切工作正常(嗯,只需几分钟的测试),但我需要一些帮助来创建可重用的函数,这将帮助我在表中建立所有关系......

我试图注释我的代码中的所有内容,所以所有解释都在那里...

<?php
function add(){

 // This is what user posted in form.
 // There are two input fields:
 // name is always only one record
 // country can be a single record or array separated with " | " characters
 // I use CodeIgniter's $this->input->post instead of $_POST[]
 $name = $this->input->post('name');
 $countries = $this->input->post('country');

 // Inserting data to first table
 $data = array('firstName' => htmlentities($name)); // preparing array for inserting
 $insert_name = $this->db->insert('names', $data); // inserting with CodeIgniter's help
 $last_inserted_ID = $this->db->insert_id(); // getting last inserted ID

 // Inserting data to second table

 // Formatting of posted string of countries
 // Users can post strings similar to this:
 // "Austria"
 // "Austria |"
 // "Austria | "
 // "Austria | Australia"
 // "Austria | Australia |"
 // "Austria | Australia | "
 // and similar variations
 // What I need here is clear array with country names
 $separator = strpos($countries,"|"); // check for "|" character
 if ($separator === FALSE){ // if there is no "|" character in string
  $countries_array[] = $countries; // array is only one value (only one country)
 } else {
  $countries_array = explode(" | ", $countries); // explode my array
  if (end($countries_array) == ""){ // if last item in array is ""
   array_pop($countries_array); // eliminate last (empty) item
  }
 }

 // Now, this is the part I think I will use lots of times.
 // I would like to make this a separate function so I could use it in many places :)
 // I would pass to that function few values and I would use one of them
 // to call different functions in this same class.
 // I guess I should pass data ($countries_array) and function names I wish to call?????? This is problematic part for my brain :))
 // Check the comments below...
 for ($i = 0; $i < sizeof($countries_array); $i++){
  $insertIDS = array(); // this will be an array of IDs of all countries
  $tempdata = $this->get_countries($countries_array[$i]); // query which looks if there is a country with specific name
                // Right here, instead of calling $this->get_countries
                // I would like to call different functions, for example
                // $this->get_links($links_array[$i])
                // or $this->get_categories($categories_array[$i])
                // etc.
  if(sizeof($tempdata) != 0){ // so, if a record already exists
   foreach ($tempdata as $k => $v){
    $insertIDS[] = $k; // insert those IDs in our array
   }
  } else { // and if a record does not exist in db
   $this->add_country($countries_array[$i]); // add it as a new record...
               // This is also one of the places where I would call different functions
               // for example $this->add_link($links_array[$i])
               // or $this->add_categories($categories_array[$i])
               // etc.
   $insertIDS[] = $this->db->insert_id(); // ...get its ID and add it to array
  }

  // Finally, insert all IDs into junction table!
  foreach ($insertIDS as $idKey => $idValue){
   $this->add_names_countries($last_inserted_ID, $idValue); // Another place for calling different functions
                  // example $this->add_names_links($last_inserted_ID, $idValue)
                  // etc.
  }
 }

}
?>

好吧,现在看看这段代码,我发现我也可以将格式化部分也放在该函数中,但这现在并不那么重要...

非常感谢您的任何帮忙解决这个问题!!

This is my first time I am trying to make something seriously with relational db in MySQL and some kind of CMS created in PHP with CodeIgniter.
I came to the part where I have to insert some data in few many-to-many related tables.
In my code everything works fine (well, with just few minutes of testing), but I need some help with creating reusable function which will help me a lot to make all relations in my tables...

I tried to comment everything in my code, so all explanations are in there...

<?php
function add(){

 // This is what user posted in form.
 // There are two input fields:
 // name is always only one record
 // country can be a single record or array separated with " | " characters
 // I use CodeIgniter's $this->input->post instead of $_POST[]
 $name = $this->input->post('name');
 $countries = $this->input->post('country');

 // Inserting data to first table
 $data = array('firstName' => htmlentities($name)); // preparing array for inserting
 $insert_name = $this->db->insert('names', $data); // inserting with CodeIgniter's help
 $last_inserted_ID = $this->db->insert_id(); // getting last inserted ID

 // Inserting data to second table

 // Formatting of posted string of countries
 // Users can post strings similar to this:
 // "Austria"
 // "Austria |"
 // "Austria | "
 // "Austria | Australia"
 // "Austria | Australia |"
 // "Austria | Australia | "
 // and similar variations
 // What I need here is clear array with country names
 $separator = strpos($countries,"|"); // check for "|" character
 if ($separator === FALSE){ // if there is no "|" character in string
  $countries_array[] = $countries; // array is only one value (only one country)
 } else {
  $countries_array = explode(" | ", $countries); // explode my array
  if (end($countries_array) == ""){ // if last item in array is ""
   array_pop($countries_array); // eliminate last (empty) item
  }
 }

 // Now, this is the part I think I will use lots of times.
 // I would like to make this a separate function so I could use it in many places :)
 // I would pass to that function few values and I would use one of them
 // to call different functions in this same class.
 // I guess I should pass data ($countries_array) and function names I wish to call?????? This is problematic part for my brain :))
 // Check the comments below...
 for ($i = 0; $i < sizeof($countries_array); $i++){
  $insertIDS = array(); // this will be an array of IDs of all countries
  $tempdata = $this->get_countries($countries_array[$i]); // query which looks if there is a country with specific name
                // Right here, instead of calling $this->get_countries
                // I would like to call different functions, for example
                // $this->get_links($links_array[$i])
                // or $this->get_categories($categories_array[$i])
                // etc.
  if(sizeof($tempdata) != 0){ // so, if a record already exists
   foreach ($tempdata as $k => $v){
    $insertIDS[] = $k; // insert those IDs in our array
   }
  } else { // and if a record does not exist in db
   $this->add_country($countries_array[$i]); // add it as a new record...
               // This is also one of the places where I would call different functions
               // for example $this->add_link($links_array[$i])
               // or $this->add_categories($categories_array[$i])
               // etc.
   $insertIDS[] = $this->db->insert_id(); // ...get its ID and add it to array
  }

  // Finally, insert all IDs into junction table!
  foreach ($insertIDS as $idKey => $idValue){
   $this->add_names_countries($last_inserted_ID, $idValue); // Another place for calling different functions
                  // example $this->add_names_links($last_inserted_ID, $idValue)
                  // etc.
  }
 }

}
?>

Well, looking at this code now, I see that I could put that formatting part also in that function, but that's not so much important right now...

Thank you very very much for any help with this!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

生生漫 2024-08-24 19:31:47

首选方法是使用表数据网关。而不是

$this->db->insert('countries', $data);

为数据库中的每个表创建类。每个表都将 CRUD 逻辑封装到类中,例如

class Countries
{
    $protected $_db;

    public function __construct($db)
    {
        $this->_db = $db;
    }

    public function save(array $countries)
    {
        $this->db->insert('countries', $countries);
    }

    // ... other methods
}

此外,我建议为此使用 transactions这是一种工作,因为所有这些东西都属于在一起,如果其中一个查询失败,您可能不想插入任何数据。我不知道 CodeIgnitor 如何处理事务,但基本上,您应该这样做:

$this->db->startTransaction();          // like try/catch for databases
$countries = new Countries($this->db);
$countries->save($countryData);
$links = new Links($this->db);
$links->save($linkData);
// ...
if($this->db->commit() === false) {     // returns true when no errors occured
    $this->db->rollback();              // undos in case something went wrong
}

虽然这不能回答您的问题如何动态调用函数(call_user_func() 可以做到这一点),像上面建议的那样做会让你的代码更可维护。

您的问题有点模糊,您是否想按顺序运行所有功能,或者只是想根据用户提交的内容进行交换。对于第一种情况,使用事务方法。对于第二种情况,您只需实例化适当的类并调用 save 方法即可。

The preferred way of doing this is to use a Table Data Gateway. Instead of

$this->db->insert('countries', $data);

you create classes for each Table in your database. Each table encapsulates CRUD logic into the class, e.g.

class Countries
{
    $protected $_db;

    public function __construct($db)
    {
        $this->_db = $db;
    }

    public function save(array $countries)
    {
        $this->db->insert('countries', $countries);
    }

    // ... other methods
}

In addition, I suggest to use transactions for this kind of work because all that stuff belongs together and you likely do not want to insert any data, if one of the queries fails. I don't know how CodeIgnitor handles transactions, but basically, you should do it this way then:

$this->db->startTransaction();          // like try/catch for databases
$countries = new Countries($this->db);
$countries->save($countryData);
$links = new Links($this->db);
$links->save($linkData);
// ...
if($this->db->commit() === false) {     // returns true when no errors occured
    $this->db->rollback();              // undos in case something went wrong
}

While this does not answer your question how to dynamically call a function (call_user_func() could do this), doing it like suggested above makes your code much more maintainable.

Your question is a bit vague as to if you want to run all the functions in a sequence or just want to interchange depending on what the user submitted. For the first case, use the transaction approach. For the second case, you would simply instantiate the appropriate class and call the save method.

萌辣 2024-08-24 19:31:47

不完全确定您的要求,但我认为您可能会在 call_user_func 之后:

function process($countries) {
// do stuff
}

$function_name = 'process';

call_user_func($function_name, $countries);

这样,您可以根据国家/地区列表动态分配函数。

Not entirely sure of your requirements, but I think you might be after call_user_func:

function process($countries) {
// do stuff
}

$function_name = 'process';

call_user_func($function_name, $countries);

This way, you can dynamically assign a function based on, say, the list of countries.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文