How to create a common function in moodle? - php

I want to create a common functionality in Moodle. That function will be accessible to all the pages like login, course etc. So, in which file or lib, I need to write the function and how will I access it? My function name will be like:
function addpoints() {
return $data;
}

I'd recommend creating a local plugin to hold functions like that. You will then need to call:
require_once($CFG->direct.'/local/mylocalplugin/lib.php');
addpoints();
If you are using moodle 2.6 or above, you can make use of the automatic class loading feature ( http://docs.moodle.org/dev/Automatic_class_loading ) to load your code without the require_once line, but that is a bit more fiddly to set up.

Related

Why do we need function_exists?

Why do we need to check function_exists for user defined functions? It looks ok for internal or core PHP functions but if user know and defined a function himself then why do need to check for its existance?
Below is custom user defined function
if( !function_exists( 'bia_register_menu' ) ) {
function bia_register_menu() {
register_nav_menu('primary-menu', __('Primary Menu'));
}
add_action('init', 'bia_register_menu');
}
Thanks
To make sure you don't register the same function twice, which will cause an error.
You also use if(function_exists('function_name')) when you are calling functions defined in plugins. In case you deactivated your plugin, your site will still be functional.
In dynamically loaded files using autoloaders, the file containing the function or class might not have loaded, so you need to check if it exists
This answer on the Wordpress StackExchange clarifies why you should sometimes use if function_exists around a function declaration in a theme:
The if function_exists approach allows for a child theme to override the function definition by simply defining the function themselves. Since child theme's functions.php files load first, then they will define the function first and the parent's definition will not get loaded.
I suppose it's analogous to the protected keyword in object oriented languages.
However I still wonder whether there would be any need for it around function declarations in plugins.
Imagine that you use you're URL to get the function name and call it.
Then we have the following info:
url: http://mysite.com/my/page/
When converting this url into a function name, you would do something like this:
implode('_', $myUrlPart); //my_page
The output would be "my_page" as string. But if you call this right away and the function does not exist, an error will be shown. This is where the function_exists comes in, take a look:
if (function_exists($function_name)) {
$function_name(); //the function is called
} else {
//call other function to show HTTP 404 page or something like that
}
Does this makes it a little clearer?
Because WordPress is designed so poorly it does not have any proper mechanism for autoloading modules like that, so you need to add safeguards.

How to call an external api from codeIgniter?

Hi I am facing a big problem right now in developing my application. Actually there is a function developed already in one of our previous application class file. Now we want to use that function in our new application. How can we call that function in our new controller using codeIgniter.
Note: our old application is in core PHP.
old file report.class.php....in this there is a function name get_report()
New controller ro_manager.php.......in this there is a function order_details()...
I want to call get_report() function in order_details() function......i need help in this any idea.......
Codeigniter is just a framework. You can still use native php without any problem(Paths may need a little bit modification).
Just make it as a library and load it via $this->load->library('libraryName');
or else, you can include it in naive way. create an instantiation in the controller and use it just like any other OOP project.
Creating codeigniter libraries The documentation includes all the procedure you will need (with examples).
As far I can see, you’re wanting to either create a library with this old function in, and load it in your CodeIgniter controllers; or just add the function in your controller as a private method if it’s to only ever be used in that controller.

it is possible to extend a php function?

My question is if it's possible to extend a declared function.
I want to extend mysql_function to add mysql query that insert into a table some logs : 'query' - the parameter of mysql_query, date,page...etc
My question is if it's possible to extend a declared function.
No.
You can extend a class method and call parent::methodname() to run the previous code (which is almost what you ask for), but for normal functions, there is no way to do this.
There are some esoteric PHP extensions that allow overriding functions, but I assume that's not what you need and their use is rarely practical.
What you probably want to do is create a new function, and call the existing function in it.
No, you cannot do that. Either enable the MySql Query Logs or wrap the code doing the queries into a Logging Decorator or use an abstraction like Zend_Db that can take a Profiler or use a transparent logging plugin for mysqlnd
You need to write a function that will take your query, log the sql first, runs your query, then return the results.
E.G
<?php
function mysql_query_log($sql)
{
mysql_query('insert into .... values ...');
$r = mysql_query($sql);
$results;
//do the normal thing you do with mysql here
return $results;
}
This is not extending a function though, you can only extend a class
It's not possible.
You should have created your own API (or use an existing one) to access the DB so when you need logging you can simply enhance your own API function. It also comes very handy if you need some custom error handling function. Refactor the code.
Well.. PHP says this: http://php.net/manual/en/function.override-function.php
from http://php.net/manual/en/function.rename-function.php
bool rename_function ( string $original_name , string $new_name )
Renames a orig_name to new_name in the global function table. Useful
for temporarily overriding built-in functions.
I believe that if you rename the original to original_mysql_query, then add your replacement function which does your logging and then calls original_mysql_query etc, that you will achieve your goal, assuming that you have the way to inject the rename on every page that will call MySQL_query. Most large sites have common code that is included at the top of every page that could do that for you.
There is also a built in php function called override_function (mentioned by ChrisH). It is not fully documented in the php man page but the user comments below the doc give you the information that you need to use it if you prefer it to the rename_function function. There was a discussion about being limited to one override if you needed to call the original function from the replacement. Using the rename_function instead of the override function eliminates that potential restriction.

Importing external php files in Yii

I've got some files using raw php (including config files) that's used for the automatic mailing stuff in my server.
Suppose inside this file I define a couple of constants (define(...)) and an array filled with database connection info, like user, host and so).
The website is done using Yii, so it also uses a config file.
These raw files can be placed anywhere (inside protected, outside, at the same level of index.php, whatever).
Now the problem comes that I've got a different configuration file (and different users/password for databases, and so) outside Yii, but I need to use it in some places inside Yii, too.
Is there a clear way to import these files to a controller? I've done it placing them inside extensions, but the raw functions didn't work from there.
The best approach would be to see if you can put your custom code into class files and put those in the components directory or similar and convert your files to classes (if they aren't already). That way you can get at your data without a lot of mixing of code which is going to be hard to maintain.
Simple approach will be to place the files in extensions and add the path of the extensions to your yii configuration. Then make a controller and call methods from its actions. Lets consider an example of swiftmailer. Here is a custom controller you can use.
class mailerController extends Controller{
public function actions()
{
return array(
//can add other actions here
);
}
public function actionIndex(){
echo "use mailer?e=<email>&m=<message>&sub=<subject> to send mail from the site to the email address";
}
public static function actionSendMail($e,$m,$sub){
$content = $m ; // can use a template and then assign to content
$SM = new SwiftMailer(); //the external method, should be present in include path
// Get config
$mailHost = Yii::app()->params['mailhost'];
$mailPort = 25; // Optional
$Transport = $SM->smtpTransport($mailHost, $mailPort);
$Mailer = $SM->mailer($Transport);
$Message = $SM
->newMessage($sub)
->setFrom(Yii::app()->params['sitemail'])
->setTo($e)
->addPart($content, 'text/html');
return ( $Mailer->send($Message));
} }
once your controller is ready, it can be called like
yoursite.com/mailer?e=<email>&m=<message>&sub=<subject>

Loading custom classes in CodeIgniter?

Just starting to use CodeIgniter, and I'd like to import some of my old classes for use in a new project. However, I don't want to modify them too much to fit into the CI way of doing things, and I'd like to be able to continue to use NetBeans' autocomplete functionality, which doesn't work too well with CI.
So, what is the best way to load custom classes & class files into CodeIgniter without having to use the library/model loading mechanisms?
I apologise if this is something I should be able to find quickly, but I can't seem to find what I'm after. Everything I see is just telling me how to go through CI.
To do it codeigniter way, place your custom classes in libraries folder of codeigniter. And then use it by adding that class as library in your controller like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Someclass {
public function some_function()
{
}
}
/* End of file Someclass.php */
using in controller:
$this->load->library('someclass');
checkout complete article at http://www.codeigniter.com/user_guide/general/creating_libraries.html
Libraries are easy to write but they have a few restrictions. Constructors can only take an array as a parameter and it's assumed that only one class will exist per file.
You can include any of your own classes to work with them however you want, as this is only PHP ofc :)
include APPPATH . 'classes/foo.php';
$foo = new Foo;
Or set up an __autoload() function in your config.php (best place for it to be) and you can have access to your classes without having to include them.
I'd say you at least write a wrapper class that could require the classes and instantiate the objects and make them accessible. Then you could probably autoload such library and use it as needed.
I would recommend that you at least tried to have them fit in the CI way, as moving forward this will make you life much more easy. I've been in kind of the same position and learned just this along the way.
require_once(PHYSICAL_BASE_URL . 'system/application/controllers/abc.php');
$report= new abc();
Next use the function detail in abc contoller:
$mark=$report->detail($user);
If you're just starting to use CodeIgniter, maybe you ought to check Kohana (http://kohanaframework.org/). It is very similar to CodeIgniter in many ways but it loads classes in the normal way (using new ClassName()) so Netbeans' autocompletion features should works normally.

Categories