Foro de elhacker.net

Programación => PHP => Mensaje iniciado por: Shell Root en 4 Noviembre 2011, 07:50 am



Título: Heredar varios objetos + PHP
Publicado por: Shell Root en 4 Noviembre 2011, 07:50 am
Tengo tres clases:
  • RegistrarUsuario
  • DB
  • EnviarEmail


Cuando realizo la clase RegistrarUsuario tengo que heredar los metodos de la clase DB, lo hago así:
Código
  1. class RegisterUser extends DB{}

Pero cuando necesito también heredar lo metodos de la clase EnviarEmail, como sería?


Título: Re: Heredar varios objetos + PHP
Publicado por: satu en 4 Noviembre 2011, 12:08 pm
Hola

Acabo de ver esto (http://phpsenior.blogspot.com/2006/08/herencia-mltiple-en-php5.html), no se si será correcto o es lo que buscas pues estoy empezando en PHP

Saludos


Título: Re: Heredar varios objetos + PHP
Publicado por: Shell Root en 4 Noviembre 2011, 21:08 pm
Si, eso lo ví, pero no me funciona además dice que no es recomendable hacerlo, dice algo de Interfaces, alguien tiene idea?


Título: Re: Heredar varios objetos + PHP
Publicado por: madpitbull_99 en 4 Noviembre 2011, 21:40 pm
Has planteado mal el diseño desde el principio, aunque se puede arreglar.

Mira el ejemplo que acabo de hacer:

Código
  1. <?php
  2.  
  3. class A {
  4. public $var1, $var2;
  5. public function metodoClaseA() { }
  6. }
  7.  
  8. class B  extends A{
  9. public $var3, $var4;
  10. public function metodoClaseB() { }
  11. }
  12.  
  13. class Heredero extends B {
  14. public $var5;
  15. public function metodoClaseHeredero() { }
  16. }
  17.  
  18.  
  19. $obj = new Heredero();
  20. $obj->metodoClaseA(); //Funciona
  21. print_r($obj);


Otra opción sería la siguiente:

Código
  1. <?php
  2.  
  3. class A {
  4. public $var1, $var2;
  5. public function metodoClaseA() { echo "estas en clase A"; }
  6. }
  7.  
  8. class B {
  9. public $var3, $var4;
  10. public function metodoClaseB() { }
  11. public function getMetodosClaseA() { return new A(); }
  12. }
  13.  
  14. class Heredero extends B {
  15. public $var5;
  16. public function metodoClaseHeredero() { }
  17. }
  18.  
  19.  
  20. $obj = new Heredero();
  21. $obj->getMetodosClaseA()->metodoClaseA();
  22.  
  23. print_r($obj);
  24.  
  25.  

La posible solución consiste en crear un objeto de la clase que no puedes heredar y usarlo dentro de esa clase.

Por ejemplo, si dentro de RegistrarUsuario tienes que usar los métodos de DB o EnviarEmail sólo tienes que crear un objeto de una de
esas clases, dentro de RegistrarUsuario.



Título: Re: Heredar varios objetos + PHP
Publicado por: Shell Root en 5 Noviembre 2011, 06:31 am
Ok, Gracias.

Provecho para preguntar, si alguien tiene ejemplo real, de como diseñarlo.

Lo único que no entiendo es como que esta mal planteado el diseño.


Título: Re: Heredar varios objetos + PHP
Publicado por: [u]nsigned en 7 Noviembre 2011, 22:07 pm
http://php.net/manual/es/language.oop5.interfaces.php

Las interfaces son algo asi como 'clases abstractas' que no pueden heredar ni crear objetos, solamente definen prototipos de funciones, y luego el codigo de cada funcion es escrito en la clase que implemente la interfaz.


Título: Re: Heredar varios objetos + PHP
Publicado por: WHK en 9 Noviembre 2011, 00:52 am
Yo lo hago así:

Código:
class main{
 var $need;
 function __construct(){
  $this->need = array('class1','class2');
 }

}

...

function load_lib($lib){
 $this->$lib = new $lib();
 foreach($this->$lib->need as $need){
  $this->$lib->$need = new $need();
 }
}

Se que no es lo mas adecuado ni lo mas correcto pero yo suelo utilizar funciones que recursivamente agregan las librerias que requiero desde un array dentro del constructor, es parte de mi framework y se cargan inmediatamente cuando las llamo y quedan establecidas en la clase principal del sistema incluyendo las incluidas de forma recursiva, o sea, cada clase cargada a su ves hereda todas las demás clases por defecto y puedes llamarlas desde donde te sea mas cómodo.

Mira, dale un vistazo al archivo principal de mi framework:
Código
  1. <?php if($_SERVER['SCRIPT_FILENAME'] == __file__) exit;
  2. /* FrameworkDrawCoders : 3.3 / Last modification : 20-Oct-2011 Class version : 1.6 */
  3.  
  4. /* Execute */
  5. $system = new system();
  6.  
  7. $system->prepare_permalinks();
  8. $system->stripslash_superglobals();
  9.  
  10. $system->load_plugins('pre');
  11. $system->load_module();
  12. $system->load_theme();
  13. $system->load_plugins('pos');
  14. $system->theme->show_all();
  15. $system->terminate();
  16. /* End execute */
  17.  
  18. class system{
  19. /* Class vars */
  20. var $sidebars;
  21. var $main_menu;
  22.  
  23. /* System Vars */
  24. var $last_error;
  25.  
  26. /* Default libs */
  27. var $conf;
  28. var $str;
  29. var $path;
  30. var $headers;
  31.  
  32. function __construct(){
  33. include(dirname(__file__).'/configuration.php');
  34. $this->conf = new configuration();
  35. $this->conf->apply();
  36. /* Global functions */
  37. $this->load_global_libs();
  38. $this->headers->ctype_html();
  39. }
  40.  
  41. function load_global_libs(){
  42. /* Make matrix */
  43. foreach($this->conf->load_default_libs as $lib){
  44. include_once($this->conf->lib_dir .$lib.'.php');
  45. if(!is_object($this->$lib)){
  46. $this->$lib = new $lib();
  47. $this->$lib->conf = $this->conf;
  48. }
  49. }
  50. /* Inject objects */
  51. foreach($this->conf->load_default_libs as $lib){
  52. foreach($this->conf->load_default_libs as $inject){
  53. if((is_object($this->$inject)) and ($inject != $lib)){
  54. $this->$lib->$inject = $this->$inject;
  55. }
  56. }
  57. }
  58. }
  59.  
  60. function load_ret_lib($lib){
  61. if(!$lib = preg_replace('|[^A-Za-z0-9_]|i', '', $lib))
  62. return false;
  63.  
  64. if(!include_once($this->conf->lib_dir .$lib.'.php'))
  65. return false;
  66. $retOB = new $lib;
  67.  
  68. /* Import default libs */
  69. foreach($this->conf->load_default_libs as $lib_def){
  70. if($lib_def != $lib){
  71. if($this->$lib_def)
  72. $retOB->$lib_def = $this->$lib_def;
  73. else{
  74. include_once($this->conf->lib_dir .$lib_def.'.php');
  75. $retOB->$lib_def = new $lib_def;
  76. }
  77. }
  78. }
  79.  
  80. /* Configurations */
  81. $retOB->conf = $this->conf;
  82.  
  83. /* Import libs needs */
  84. if(is_array($retOB->libs_need)){
  85. foreach($retOB->libs_need as $import){
  86. if($this->$import)
  87. $retOB->$import = $this->$import;
  88. else{
  89. include_once($this->conf->lib_dir .$import.'.php');
  90. $retOB->$import = new $import;
  91. }
  92. }
  93. }
  94. return $retOB;
  95. }
  96.  
  97. function load_lib($lib){
  98. if(!$lib = preg_replace('|[^A-Za-z0-9_]|i', '', $lib))
  99. return false;
  100. if(is_object($this->$lib))
  101. return $this->$lib;
  102.  
  103. if(!include_once($this->conf->lib_dir .$lib.'.php'))
  104. return false;
  105. $this->$lib = new $lib();
  106.  
  107. /* Import default libs */
  108. foreach($this->conf->load_default_libs as $lib_def){
  109. if((is_object($this->$lib_def)) and ($lib_def != $lib)){
  110. $this->$lib->$lib_def = $this->$lib_def;
  111. }
  112. }
  113.  
  114. /* Configurations */
  115. $this->$lib->conf = $this->conf;
  116.  
  117. /* Import libs needs */
  118. if(is_array($this->$lib->libs_need)){
  119. foreach($this->$lib->libs_need as $import){
  120. $this->load_lib($import); /* Make lib */
  121. $this->$lib->$import = $this->$import; /* Import lib */
  122. }
  123. }
  124. return $this->$lib;
  125. }
  126.  
  127. function load_plugins($prefix){
  128. if($plugins = glob($this->path->plugins('local').$prefix.'*.php')){
  129. foreach($plugins as $plugin){
  130. include_once($plugin);
  131. }
  132. }
  133. }
  134.  
  135. function load_module(){
  136. if($inc = $this->mod_selected()){
  137. $this->conf->module_used_dir = $this->path->modules('relative') .$inc.'/';
  138. $this->conf->module_selected = $inc;
  139. }else{
  140. $this->conf->last_code_status = 404;
  141. $this->conf->module_used_dir = $this->path->modules('relative') .'status/';
  142. $this->conf->module_selected = 'status';
  143. }
  144. include_once($this->path->actual_mod('local') .'index.php'); /* Main file of module */
  145. $this->theme->buffer_module = ob_get_contents();
  146. }
  147.  
  148. function load_component($file){
  149. if(file_exists($inc = $this->path->actual_mod('local') .'/__layout/'.$file.'.php')){
  150. include_once($inc); /* Actual mod */
  151.  
  152. }elseif(file_exists($inc = $this->path->modules('local') .$this->conf->main_mod .'/__layout/'.$file.'.php')){
  153. include_once($inc); /* Main mod */
  154.  
  155. }
  156. $buff = ob_get_contents();
  157. return $buff;
  158. }
  159.  
  160. function load_theme(){
  161. if($this->conf->use_theme){
  162.  
  163. /* Load components */
  164. $this->theme->buffer_footer = $this->load_component('footer');
  165. $this->load_component('main_menu');
  166. $this->load_component('sidebars');
  167.  
  168. /* Load theme */
  169. $this->conf->theme_dir = $this->conf->themes_dir .$this->conf->id_theme .'/';
  170. if(file_exists($this->path->theme('local').'index.php')){
  171. include($this->path->theme('local').'index.php');
  172. $this->theme->buffer_module = ''; /* less memory */
  173. $this->theme->buffer_theme = ob_get_contents();
  174. }else
  175. $this->theme->buffer_theme = 'Theme not exist.';
  176.  
  177. }
  178. }
  179.  
  180. function terminate(){
  181. if(is_object($this->sql)){
  182. if($this->sql->handle)
  183. $this->sql->close();
  184. }
  185. }
  186.  
  187. function mod_selected(){
  188. if(!isset($_GET[$this->conf->var_get]))
  189. return $this->conf->main_mod;
  190. if(!$inc = preg_replace('|[^A-Za-z0-9_,-]|i', '', $_GET[$this->conf->var_get]))
  191. return false;
  192. if(!file_exists($this->conf->modules_dir .$inc.'/index.php'))
  193. return false;
  194. return $inc;
  195. }
  196.  
  197. function stripslash_superglobals(){
  198. $_GET = array_map('stripslashes', $_GET);
  199. $_POST = array_map('stripslashes', $_POST);
  200. $_SERVER = array_map('stripslashes', $_SERVER);
  201. $_COOKIE = array_map('stripslashes', $_COOKIE);
  202. $_REQUEST = array_map('stripslashes', $_REQUEST);
  203. $_ENV = array_map('stripslashes', $_ENV);
  204. }
  205. }
  206.  
  207. function prepare_permalinks(){
  208. if(isset($_SERVER['REDIRECT_URL'])){ /* Mod rewrite -> to php */
  209. if(dirname($_SERVER['SCRIPT_NAME']) != '/')
  210. $permalink = str_replace(array(dirname($_SERVER['SCRIPT_NAME']), '.html'), '', $_SERVER['REDIRECT_URL']); // /permalink/x/aaaaa.html
  211. else
  212. $permalink = str_replace(array('.html'), '', $_SERVER['REDIRECT_URL']); // /permalink/x/aaaaa.html
  213.  
  214. if(substr($permalink, 0, 1) == '/')
  215. $permalink = substr($permalink, 1);
  216. $permalink = explode('/', $permalink);
  217.  
  218. foreach($permalink as $id => $var){
  219. if($id == 0){
  220. $_GET[$this->conf->var_get] = $var;
  221. }elseif($id % 2 == 0){
  222. $_GET[$prevar] = $var;
  223. unset($prevar);
  224. }else{
  225. $prevar = $var;
  226. }
  227. unset($id, $var);
  228. }
  229. unset($permalink);
  230. if($prevar)
  231. unset($prevar);
  232. }
  233. }
  234.  
  235. }

Después hago esto:

Código
  1. <?php
  2. $this->load_lib('paginator');
  3. $this->paginator->load_sql('select * from {prefix}users');
  4. $this->paginator->makeHtml();
  5. echo 'Con un total de '.$this->paginator->pages->toInt().' paginas.';
  6. ?>

Y si te fijas llamé a la clase paginator que se cargó dentro de la clase principal y a su ves paginator requiere por defecto la clase str que me transforma las variables a objetos para pharsearlas como por ejemplo $this->user->name->toHtml() o $this->str->_get('algo')->toHtml() y son solo recursiones simples:

Código
  1. <?php if($_SERVER['SCRIPT_FILENAME'] == __file__) exit;
  2. /*
  3. FrameworkDrawCoders : 3.*
  4. Last modification : 29-4-2011
  5. Class version : 1.3
  6. */
  7.  
  8. class user{
  9. /* System Vars */
  10. var $last_error;
  11. var $libs_need;
  12.  
  13. /* Default libs */
  14. var $conf;
  15. var $str;
  16. var $path;
  17. var $headers;
  18.  
  19. /* Libs need */
  20. var $sql;
  21.  
  22. /* Class Vars */
  23. var $is_logged = false;
  24. var $is_loaded = false;
  25. var $user_data = false;
  26.  
  27. function __construct(){
  28. $this->libs_need = array('sql'); /* Need */
  29. }
  30.  
  31. function load($arr = false){
  32. if(is_array($arr)){
  33. $find = '';
  34. $count = 0;
  35. foreach($arr as $var => $val){
  36. $val = new str($val);
  37. $find .= $var.' = "'.$val->toSql().'"';
  38. $count++;
  39. if($count != count($arr))
  40. $find .= ' and ';
  41. }
  42.  
  43. if(!$this->user_data = $this->sql->fast_select('select * from {prefix}users where '.$find.' limit 1', true))
  44. $this->last_error = array('id' => 1, 'text' => 'Value(s) dont match');
  45. else{
  46. foreach($this->user_data as $var => $val){
  47. $this->$var = new str($val);
  48. }
  49. $this->is_loaded = true;
  50. }
  51. }
  52. return $this;
  53. }
  54.  
  55. function login($arr_condition = false){
  56. if(!$this->is_loaded){
  57. $this->last_error = array('id' => 13, 'text' => 'Is not loaded');
  58. return $this;
  59. }
  60.  
  61. if(is_array($arr_condition)){
  62. if($arr_condition['password'])
  63. $arr_condition['password'] = $this->cryptPass($arr_condition['password']);
  64.  
  65. foreach($arr_condition as $var => $val){
  66. if($this->$var->val() != $val){
  67. $this->last_error = array('id' => 14, 'text' => 'Values dont match');
  68. return $this;
  69. }
  70. }
  71. } /* else{ Autologin without data } */
  72.  
  73. /* Update database */
  74. $this->update(array(
  75. 'token' => $this->makeHash(),
  76. 'last_login' => time()
  77. ));
  78.  
  79. /* Set the cookie */
  80. setcookie($this->conf->cookiename , serialize(array(
  81. 'id_user' => $this->id->toInt(),
  82. 'password' => $this->password->val(),
  83. 'token' => $this->token->val()
  84. )), false, '/');
  85.  
  86. $this->is_logged = true;
  87. return $this;
  88. }
  89.  
  90. function loadCookie(){
  91. if($cookie = unserialize(trim($_COOKIE[$this->conf->cookiename]))){
  92. $this->load(array(
  93. 'id' => (int)$cookie['id_user'],
  94. 'password' => $cookie['password'],
  95. 'token' => $cookie['token']
  96. ));
  97. if($this->is_loaded){
  98. $this->is_logged = true;
  99. $this->update(array('last_login' => time()));
  100. }
  101. }else
  102. $this->last_error = array('id' => 3, 'text' => 'No cookie to login');
  103. return $this;
  104. }
  105.  
  106. function logout(){
  107. if($this->is_loaded and $this->is_logged){
  108. $this->update(array('token' => $this->makeHash())); /* AntiHacking account->cookie */
  109. setcookie($this->conf->cookiename, '', false, '/');
  110. $this->is_logged = false;
  111. foreach($this->user_data as $var => $val){
  112. unset($this->$var);
  113. }
  114. $this->user_data = '';
  115. $this->is_loaded = false;
  116. }else{
  117. $this->last_error = array('id' => 16, 'text' => 'No cookie to login');
  118. }
  119. return $this;
  120. }
  121.  
  122. function newAccount($arr_data){
  123. /* Set default data */
  124. if($arr_data['password']) $arr_data['password'] = $this->cryptPass($arr_data['password']);
  125. if(!$arr_data['token']) $arr_data['token'] = $this->makeHash();
  126. if(!$arr_data['register_date']) $arr_data['register_date'] = time();
  127.  
  128. if(!$this->sql->update('users', $arr_data))
  129. $this->last_error = array('id' => 8, 'text' => $this->sql->last_error['text']);
  130. return $this;
  131. }
  132.  
  133. function update($arr_data){
  134. if(!$this->is_loaded){
  135. $this->last_error = array('id' => 9, 'text' => 'No data loaded for update');
  136. return $this;
  137. }
  138.  
  139. if($arr_data['password'])
  140. $arr_data['password'] = $this->cryptPass($arr_data['password']);
  141.  
  142. foreach($arr_data as $var => $val){
  143. $this->user_data[$var] = $val;
  144. $this->$var = new str($val);
  145. }
  146. return $this->sql->update('users', $arr_data, 'id = '.$this->id->toInt());
  147. }
  148.  
  149. function delete(){
  150. if($this->sql->raw('delete from {prefix}users where id = '.$this->id->toInt())){
  151. $this->is_logged = false;
  152. $this->is_loaded = false;
  153. if(is_array($this->user_data)){
  154. foreach($this->user_data as $var => $val){
  155. unset($this->$var);
  156. }
  157. $this->user_data = false;
  158. }
  159. }else
  160. $this->last_error = array('id' => 11, 'text' => 'Error in delete user. Db error');
  161. }
  162.  
  163. function makeHash($length = 10){
  164. return substr(sha1($length.rand(11,99).microtime()), 0, (int)$length);
  165. }
  166.  
  167. function cryptPass($password){
  168. return sha1($password.sha1("\xa1__".$password)."__\x01");
  169. }
  170.  
  171. function levelPass($password = false){
  172. if(!$password) return 0;
  173. $level = 0;
  174. if(strlen($password) >  1) $level += 1;
  175. if(strlen($password) >  2) $level += 1;
  176. if(strlen($password) >  3) $level += 3;
  177. if(strlen($password) >  4) $level += 5;
  178. if(strlen($password) >  5) $level += 10;
  179. if(strlen($password) >  6) $level += 10;
  180. if(strlen($password) >  7) $level += 10;
  181. if(strlen($password) >  10) $level += 10;
  182. if(strlen($password) >  20) $level += 25;
  183. if(!ctype_alnum(payload)) $level += 25;
  184. return $level;
  185. }
  186.  
  187. }
  188.  

Si te fijas en este caso no fue necesario solicitar la clase str en el array porque el sistema ya carga algunas clases por default en el archivo de configuraciones que son str, conf y path.

Si le hago print_r() a la clase se pueden ver las recursiones, si modificas $this->conf es lo mismo que modificar $this->algo->conf

Citar
print_r($this->user); exit;
...
[str] => str Object
 *RECURSION*
                    [path] =>
                    [headers] => headers Object
                        (
                            [last_error] =>
                            [libs_need] =>
                            [conf] => configuration Object
                                (
                                    [script_url] => http://127.0.0.1/x/index.php
...