I'm writing a plugin, and for the most part I'm following the  with the addition of autoloading and namespacing.  When running the main class, where you include methods to run in the constructor  function run_plugin_name() {     $plugin = new Plugin_Name();     $plugin-&gt;run(); } run_plugin_name();   in the Plugin_Name class we have  class Plugin_Name {      protected $loader;      protected $plugin_name;      protected $version;      public function __construct() {         if ( defined( 'PLUGIN_NAME_VERSION' ) ) {             $this-&gt;version = PLUGIN_NAME_VERSION;         } else {             $this-&gt;version = '1.0.0';         }         $this-&gt;plugin_name = 'plugin-name';         $this-&gt;load_dependencies();         $this-&gt;set_locale();         $this-&gt;define_admin_hooks();         $this-&gt;define_public_hooks();     } }   I am wondering what is the best practice, and if there is any benefit if I define the objects that will be used in the add_action / add_filter methods inside the constructor like  public function __construct() {     if ( defined( 'PLUGIN_NAME_VERSION' ) ) {       $this-&gt;version = PLUGIN_NAME_VERSION;     } else {       $this-&gt;version = '1.0.0';     }     $this-&gt;plugin_name = 'plugin-name';      $this-&gt;admin = new Admin( $this-&gt;plugin_name, $this-&gt;version );      $this-&gt;load_dependencies();     $this-&gt;set_locale();     $this-&gt;define_admin_hooks();     $this-&gt;define_public_hooks(); }   and then use this inside, say define_admin_hooks() method  private function define_admin_hooks() {     $this-&gt;loader-&gt;add_action( 'admin_enqueue_scripts', $this-&gt;admin, 'enqueue_styles' );     $this-&gt;loader-&gt;add_action( 'admin_enqueue_scripts', $this-&gt;admin, 'enqueue_scripts' ); }   Or should I do it like it's done in the plugin boilerplate  private function define_admin_hooks() {     $plugin_admin = new Admin( $this-&gt;get_plugin_name(), $this-&gt;get_version() );     $this-&gt;loader-&gt;add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_styles' );     $this-&gt;loader-&gt;add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts' ); }   The reason I'm asking is because I have several methods where I add my actions and filters, based on the plugin functionality, and there are some classes that I'm using in both methods. So it seems better to have them in the constructor and then just use them in the methods.  That way I'm not breaking the DRY principle.  Is my reasoning correct?
123592
I've created a plugin, and of course being me, I wanted to go with a nice OO approach. Now what I've been doing is to create this class and then just below create an instance of this class:  class ClassName {      public function __construct(){      } }  $class_instance = new ClassName();     I'm assuming there is a more WP way to have this class initiated, and then I came across people saying that they prefer to have an init() function than a __construct() one. And similarly I found the a few people using following hook:  class ClassName {      public function init(){      } } add_action( 'load-plugins.php', array( 'ClassName', 'init' ) );   What is generally considered the best way to create a WP class instance on load and have this as a globally accessibly variable?  NOTE: As an interesting side point, I've noticed that while register_activation_hook() can be called from within the __construct, it cannot be called from within the init() using the second example. Perhaps someone could enlighten me on this point.  Edit: Thanks for all the answers, there clearly is a fair bit of debate as to how handle the initialization within the class itself, but I think there's generally a pretty good consensus that add_action( 'plugins_loaded', ...); is the best way to actually kick it off...  Edit: Just to confuse matters, I've also seen this used (although I wouldn't use this method myself because turning a nicely OO class into a function seems to defeat the point of it):  // Start up this plugin add_action( 'init', 'ClassName' ); function ClassName() {     global $class_name;     $class_name = new ClassName(); }
107722
Is there some equivalent of "friend" or "internal" in php? If not, is there any pattern to follow to achieve this behavior?   Edit: Sorry, but standard Php isn't what I'm looking for. I'm looking for something along the lines of what ringmaster did.  I have classes which are doing C-style system calls on the back end and the juggling has started to become cumbersome. I have functions in object A which take in object B as a parameter and have to call a method in object B passing in itself as an argument. The end user could call the method in B and the system would fall apart.
109435
What is the syntax and which namespace/class needs to be imported? Give me sample code if possible. It would be of great help.
112144
Use case:  I have a custom block:  /**  * Provides a 'Hello' Block  *  * @Block(  *   id = "my",  *   admin_label = @Translation("My Block"),  * )  */ class MyBlock extends BlockBase {    /**    * {@inheritdoc}    */   public function build() {      $build = array(       '#markup' =&gt; 'SOME WEIRD ADS HTML HERE'     );      SOME_COOL_STUFF_TO_ADD_INLINE_JAVASCRIPT_TO_THE_CLOSING_BODY_TAG      return $build;   } }   Is there a way to add inline javascript to the end of the page just when this block is rendered anywhere (in theme or panel page)?
82741
Has anyone used  and/or PHP namespaces within a plugin or theme?  Thoughts on using them? Any harm? Pitfalls?  Note: namespaces are PHP 5.3+ only. Assume, for this question, that you know you'll be dealing with servers that you know have PHP 5.3 or greater.
32861
Is this considered a good practice for rendering a Twig template and loading a CSS file from a controller?   DefaultController.php  namespace Drupal\acme\Controller;  use Drupal\Core\Controller\ControllerBase; use Drupal\Core\DependencyInjection\ContainerInjectionInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Drupal\Core\Template\TwigEnvironment;  class DefaultController extends ControllerBase implements ContainerInjectionInterface  {   /**   * @var Drupal\Core\Template\TwigEnvironment   */   protected $twig;    public function __construct(TwigEnvironment $twig)   {     $this-&gt;twig = $twig;   }    public static function create(ContainerInterface $container)   {     return new static(       $container-&gt;get('twig')     );   }    /**    * hello    * @param  string $name    * @return string    */   public function hello($name)    {      $template = $this-&gt;twig-&gt;loadTemplate(       drupal_get_path('module', 'acme') . '/templates/hello.html.twig'     );      $markup = [       '#markup' =&gt; $template-&gt;render([ 'name' =&gt; $name ]),       '#attached' =&gt; [ 'css' =&gt; [           drupal_get_path('module', 'acme') . '/assets/css/acme.css'         ]       ]     ];      return drupal_render($markup);   } }   acme.routing.yml  acme_hello:   path: '/acme/hello/{name}'   defaults:     _content: '\Drupal\acme\Controller\DefaultController::hello'     _title: 'acme Title'   requirements:     _permission: 'access content'   hello.html.twig  &lt;div class="acme-hello-text"&gt;   &lt;h1&gt;Hello {{ name }}!&lt;/h1&gt; &lt;/div&gt;
112966
I want to make sure all of the data in my plugins/themes is handled securely  before entering the database and before being output to the browser. My problem is that there are situations where the API handles the sanitization for you -- like when saving post meta fields -- and others where the plugin/theme author is wholly responsible for doing it -- like when saving custom settings.  For the scope of this question, I'm not concerned about validating data at the domain level -- e.g., checking that an Age field on a form is between 0 and 120, or that an e-mail address is valid. I'm only concerned about security -- e.g., escaping SQL queries to avoid SQL injection when saving to the database, or sanitizing data that's output to HTML templates to avoid XSS.  For output sanitization, I know that you always need to use functions like esc_html() and esc_attr() when echo'ing variables into HTML templates. But, what about when using ? Do they all sanitize the output already? If so, for which context (general HTML, tag attributes, etc)? Some functions have variants for different contexts (like the_title_attribute(), but most don't.  For input sanitization, I know that I need to use $wpdb-&gt;prepare() when making manual queries, but what about when using the Settings API to create a plugin settings page, or saving post meta fields for a custom post type?  Right now I've just been digging through Core and reading tutorials every time I use a function to find out if it sanitizes or not, but that's error-prone and time consuming. I'm hoping to find some kind of comprehensive list of all the possible situations and whether or not the API handles it. e.g.,  API validates/sanitizes   Saving post meta with update_postmeta() Saving user meta with update_user_meta() Outputting a post title - use the contextually appropriate variant of the_title() etc   You have to manually validate/sanitize   Saving plugin options with the Settings API. Pass a callback as the 3rd parameter of register_setting(). Direct database queries: Wrap the query in $wpdb-&gt;prepare(). Outputting variables in HTML. Use esc_attr(), esc_html(), etc etc   I'd also be interested to understand why the API provides it in certain situations, but not others. I'm assuming it has something to do with the unknown nature of the data, but would love to hear a thorough explanation.
45531
For example, I rarely need:  using System.Text;   but it's always there by default. I assume the application will use more memory if your code contains unnecessary . But is there anything else I should be aware of?  Also, does it make any difference whatsoever if the same using directive is used in only one file vs. most/all files?    Edit: Note that this question is not about the unrelated concept called a , designed to help one manage resources by ensuring that when an object goes out of scope, its  method is called. See .
42899
This question might be wrong, I am not sure about it. Because I am not clear on this.  I know add_action it is used to to hook our function to the specified function. For example add_action('wp_head'.'myfunc'); now what ever code in myfunc will be executed in the wp_head(). This is clear but i am having doubt in do_action what it does?  I think it is used to create our own hook like already available hooks(wp_head,wp_footer,..etc) If i am correct can anyone show me a simple understandable answer with simple example.  I have tried the difference in internet but all are pointing to difference between add_action and add_filter. I don't want to go there because first i want to clarify this and then I’ll move there.  Can anybody help me?  EDIT after Question POST  function custom_register() {     echo '&lt;script&gt;jQuery(document).ready(function(){alert("Learning Hooks");});&lt;/script&gt;';  } do_action('custom');  add_action('custom','custom_register');   I tried this in plugin but i didn't get the alert message.  But when i hook the same function with wp_head then it is working fine  /******************working****************/ add_action('wp_head','custom_register');
54857
I want to generate the html elements and their classes to fit my styling of the main menu.    I'm confused by all the near-possibilities offered in the api documentation and by looking at core themes etc. and still can't quite see what I have to do, or where I have to do it. I would be very grateful for clear pointers to:     which php functions I have to write;  which variables I need to add / update;  in which files the functions will go.   Presumably, in MYTHEME.theme I will need a preprocess function of some sort to add to the attributes and item.attributes variables that links.html.twig uses to print the menu ul and the menu item li's.   [Update] So far I have discovered one way to place classes on the Main Menu's ul but ideally I would like to add a class to each submenu's ul indicating the depth of the sub-menu. And I cannot locate any documentation or examples from which I can understand the generation / modifying of the main menu's individual link items.    This function goes into the file  MYTHEME.theme.  function MYTHEME_preprocess_page(&amp;$variables) {    // Pass the main menu and secondary menu to the template as render arrays.   if (!empty($variables['main_menu'])) {     $variables['main_menu']['#attributes']['id'] = 'main-menu-links';     $variables['main_menu']['#attributes']['class'] = array('links', 'clearfix', 'MYNEW_class');   }  }
19523
I'm developing a module that will rely heavily on external database queries. Is there a best practice for defining and using an external database connection throughout a module?    tells me how to make the connection, but not where to put it in a module (specific hook?) so I only have to define it once. Also, is it always necessary to do "db_set_active('YourDatabaseKey');" or can I pass an argument that will set the db to use? I'm using Drupal 7.
4622
allow you to create code which defines the methods of classes that implement it. You cannot however add any code to those methods.    allow you to do the same thing, along with adding code to the method.   Now if you can achieve the same goal with abstract classes, why do we even need the concept of interfaces?   I've been told that it has to do with OO theory from C++ to Java, which is what PHP's OO stuff is based on. Is the concept useful in Java but not in PHP? Is it just a way to keep from having placeholders littered in the abstract class? Am I missing something?
21478
I have a c++ header file containing a class. I want to use this class in several projects, bu I don't want to create a separate library for it, so I'm putting both methods declarations and definitions in the header file:     // example.h #ifndef EXAMPLE_H_ #define EXAMPLE_H_ namespace test_ns{  class TestClass{ public:     void testMethod(); };  void TestClass::testMethod(){     // some code here... }  } // end namespace test_ns #endif   If inside the same project I include this header from more than one cpp file, I get an error saying "multiple definition of test_ns::TestClass::testMethod()", while if I put the method definition inside the class body this does not happen:  // example.h #ifndef EXAMPLE_H_ #define EXAMPLE_H_ namespace test_ns{  class TestClass{ public:     void testMethod(){         // some code here...     } };  } // end namespace test_ns #endif   Since the class is defined inside a namespace, shouldn't the two forms be equivalent? Why is the method considered to be defined twice in the first case?
108226
I'm trying to write a function that formats every (string) member/variable in an object, for example with a callback function. The variable names are unknown to me, so it must work with objects of all classes.  How can I achieve something similar to array_map or array_walk with objects?
55703
I want to write several classes, most of them will use KOMA classes as base class.  However I stumbled upon the problem that some options (mainly concerned with layout) are not processed if given in the wrapper class:    \begin{filecontents}{test.cls}     \ProvidesClass{test}[2015/01/01]     \DeclareOption*{\PassOptionsToClass{\CurrentOption}{scrartcl}}     \ProcessOptions\relax     \LoadClass[paper=a5]{scrartcl}   \end{filecontents}  \documentclass{test}  \usepackage{blindtext}  \begin{document}   \section{Test}   \blindtext \end{document}   This results in   LaTeX Warning: Unused global option(s):     [paper=a5]  If i give the option as \documentclass[paper=a5]{test} it is used correctly, because I pass the options to scrartcl. However I want to change the defaults for the layout.   How can I achieve this?
78770
When authoring a library in a particular namespace, it's often convenient to provide overloaded operators for the classes in that namespace.  It seems (at least with g++) that the overloaded operators can be implemented either in the library's namespace:  namespace Lib { class A { };  A operator+(const A&amp;, const A&amp;); } // namespace Lib   or the global namespace  namespace Lib { class A { }; } // namespace Lib  Lib::A operator+(const Lib::A&amp;, const Lib::A&amp;);   From my testing, they both seem to work fine.  Is there any practical difference between these two options?  Is either approach better?
54835
I'm used to writing classes like this:  public class foo {   private string mBar = "bar";   public string Bar {     get { return mBar; }     set { mBar = value; }   }   //... other methods, no constructor ... }   Converting Bar to an auto-property seems convenient and concise, but how can I retain the initialization without adding a constructor and putting the initialization in there?  public class foo2theRevengeOfFoo {   //private string mBar = "bar";   public string Bar { get; set; }   //... other methods, no constructor ...   //behavior has changed. }   You could see that adding a constructor isn't inline with the effort savings I'm supposed to be getting from auto-properties.  Something like this would make more sense to me:  public string Bar { get; set; } = "bar";