Global MySQL query in Codeigniter - mysql

In an attempt to try and narrow my query down, I'm still very new to Codeigniter framework...
I want to define global variables (eg. in autoloaded helpers) and use global mysql queries throughout my site - but I don't understand how to do the latter (global mysql queries).
I understand the concept of defining single variables in a helper... and I understand the concept of creating a single mysql query in a model, loading it in a controller and using it in a view file (with a foreach loop).
How (and where) do I create a mysql query that can be autoloaded (or whatever) and used anywhere on my site - without the need to load it in every controller?

this might help.. models would probably be your best bet. below i have given some insite on how to use controlelrs/models/libraries in general, i would put my mysql code into the appropriate model file. and call it via any controller
// Library/profiles.php
class My_library
{
protected $CI;
public function __construct()
{
$this->CI =& get_instance(); // Existing Code Igniter Instance
}
public function my_lib_method()
{
// Your Code Here
// can communicate back with CI by using $this->CI
// $this->CI->load->view(....);
// $this->CI->load->model(...);
// ETC
}
}
// models/my_model.php
class My_model extends CI_Model{
public function my_mdl_method(){
// Your Code Here
}
}
// controllers/my_controller.php
class My_controller extends CI_Controller
{
public function my_ctrl_method(){
$this->load->library('my_library');
$this->load->model('my_model');
// calling a library method
$this->my_library->my_lib_method();
// calling a model method
$this->my_model->my_mdl_method();
}
}

Related

Why ths php dynamic object class creation is not working?

I am trying to create a class (working as factory class) in my Zend Expressive APP as follows:
declare(strict_types=1);
namespace App\Install\Factory;
use App\Install\Model as Models;
use App\Install\Abstracts\AttributeInterface;
class AttributeEntityFactory{
public static function create($type1 ='Attribute') : AttributeInterface
{
$resolvedClass = "Models\\$type1";
$resolvedClass1 = 'Models\\'.$type1;
//return new $resolvedClass();
//return new $resolvedClass1();
return new Models\Attribute();
}
}
The above code works perfectly for me. However, if try to use any of the other two return statements it shows
Class 'Models\Attribute' not found
How can I achieve dynamic instantiation?
The attribute class code is as follows:
namespace App\Install\Model;
use App\Install\Abstracts\AttributeInterface;
class Attribute implements AttributeInterface
{
protected $attribute;
public function setAttribute($attribute)
{
$this->attribute = $attribute;
}
public function getAttribute()
{
return $this->attribute;
}
}
My PHP version is:
PHP 7.2.13 (cli) (built: Dec 14 2018 04:20:16) ( NTS )
you may need to pass in the full namespace?
"App\Install\Model\" . $type1;
and more...
the model Attribute you have is in the namespace App\Install\Model, and the object you are trying to create is from Models\\ . $type1
maybe you need to change Models to Model
Personally, I would avoid such factory implementation because of several reasons:
It involves magic.
Less predictable code.
Harder to read for both humans and IDE's (E.g: PHPStorm would not find the usages of Attribute class in such code when you need to find it)
Harder to analyze using static analyzers
Instead, I would rewrite this to a more explicit factory, even if I had dozens of different classes in App\Install\Model namespace:
<?php declare(strict_types=1);
namespace App\Install\Factory;
use App\Install\Model as Models;
class AttributeEntityFactory
{
public static function create($type = 'Attribute') : AttributeInterface
{
switch ($type) {
case 'Attribute':
return new Models\Attribute();
case 'SomethingElse':
return new Models\SomethingElse();
default:
throw new \InvalidArgumentException(
sprintf('An unknown type %s requested from %s', $type, __METHOD__)
);
}
}
}
As a rule of thumb:
Never compose classnames / namespaces using strings concatenated with variables / parameters / constants whatever.
Never call methods in such way, too.
You'll thank me when your application/business/codebase grows enough.

How to get session in all pages.? codeigniter

Here I want to use session in my all pages any one can help me on this topic. some says create a custom controller in library, and/or use helper/hook, I don't know what will work.
If any one have a little example code and little desc. then please share here.
How can I use session in all pages.?
From the CodeIgniter documentation
Sessions will typically run globally with each page load, so the
Session class should either be initialized in your controller
constructors, or it can be auto-loaded by the system. For the most
part the session class will run unattended in the background, so
simply initializing the class will cause it to read, create, and
update sessions when necessary.
To initialize the Session class manually in your controller
constructor, use the $this->load->library() method:
$this->load->library('session');
So, in order to initialize the Session library in ALL your controllers, the best idea is to have a custom "general controller"
<?php
class MyController extends CI_Controller {
public function __construct()
{
$this->load->library('session');
}
}
and then have all your contollers extend not the default CI_Controller, but your "MyContoller", like in
<?php
class Blog extends MyController {
public function index()
{
echo 'Hello World!';
}
}
I hope this is what you need.

Symfony 2 Controller Action no return Response

I have been some time without programing in Synfony and I have some doubts.
Is posible that and Action Controller return a variable (for example and integer) instead of a Response Object or Json Object.
What I need is call a function inside another function in a different Controller. If the 2 functions live in the same Controller it has no problem (like this):
class AController{
public function AAction(){
$var = $this->BAction(); //Do whatever I want with $var
return Response ("Hello");
}
public function BAction(){
return 34; //return an integer instead of a Response
}
}
THE PROBLEM IS when the BAction is in another Controller. If I use a forward, Symfony expect that BAction return a Response object or a Json array, but I only want to return a simple variale.
Is this posible?? Return a simple integer...
Thanks a lot!!
No a Action must return a Response Object. But if you have two controllers (that will say two different classes) then you could create a service.
app/config/config.yml
services:
app.my_ownservice:
class: AppBundle\Services\OwnService
arguments:
entityManager: "#doctrine.orm.entity_manager"
app/Services/OwnService.php
namespace AppBundle\Services;
use Doctrine\ORM\EntityManager;
class OwnService {
/**
*
* #var EntityManager
*/
private $em;
public function __constructor(EntityManager $entityManager)
{
$this->em = $entityManager;
}
public function doSomething(){
// you could use the entitymanager here
return 'Okay i will do something.';
}
}
And from each controller (or whatever) you can do:
$myOwnService = $this->get('app.my_ownservice');
$text = $myOwnService->doSomething();
// echo $text;
A controller should never use another controllers action. Thats not the problem that Controllers solve. Symfony business logic structure is SOA based. (https://en.wikipedia.org/wiki/Service-oriented_architecture) Therefore for custom business logic you should always use either:
Services: http://symfony.com/doc/current/book/service_container.html
Events: http://symfony.com/doc/current/components/event_dispatcher/introduction.html

Zend FlashMessenger problems

I am new to Zend framework and I have a problem.
I created a controller abstract class which implements the functions like:
protected function AddError($message) {
$flashMessenger = $this->_helper->FlashMessenger;
$flashMessenger->setNamespace('Errors');
$flashMessenger->addMessage($message);
$this->view->Errors = $flashMessenger->getMessages();
}
protected function activateErrors()
{
$flashMessenger = $this->_helper->FlashMessenger;
$flashMessenger->setNamespace('Errors');
$this->view->Errors = $flashMessenger->getMessages();
}
So for each controller I am able to use
$this->AddError($error);
And then I render $error in layout.
So I want not to deal with flashMesenger in every controller.
but I have to execute the activateErrors when each action is executed.
for example
I have an controller test
class TestController extends MyController {
public function indexAction() {
$this->AddError("Error 1");
$this->AddError("Error 2");
$this->activateErrors();
}
public function index1Action() {
$this->AddError("Esdsd 1");
$this->AddError("sddsd 2");
$this->activateErrors();
}
}
Is there a way that I could execute this activateErrors in each action for every controller at the end of action without duplicating the code.
I mean I do not want to include this code at every action. Maybe there is a way to include it in my abstract class MyController.
Anybody any Idea?
thanks
What about using a postDispatch hook, in your parent MyController ?
Quoting that page :
Zend_Controller_Action specifies two
methods that may be called to bookend
a requested action, preDispatch() and
postDispatch(). These can be useful in
a variety of ways: verifying
authentication and ACL's prior to
running an action (by calling
_forward() in preDispatch(), the action will be skipped), for instance,
or placing generated content in a
sitewide template (postDispatch()).
Maybe this might do the trick ?
I actually contributed an enhancement to FlashMessenger which provides a lot of the functionality you're looking for.

Access to global application settings

A database application that I'm currently working on, stores all sorts of settings in the database. Most of those settings are there to customize certain business rules, but there's also some other stuff in there.
The app contains objects that specifically do a certain task, e.g., a certain complicated calculation. Those non-UI objects are unit-tested, but also need access to lots of those global settings. The way we've implemented this right now, is by giving the objects properties that are filled by the Application Controller at runtime. When testing, we create the objects in the test and fill in values for testing (not from the database).
This works better, in any case much better than having all those objects need some global Settings object --- that of course effectively makes unit testing impossible :) Disadvantage can be that you sometimes need to set a dozen of properties, or that you need to let those properties 'percolate' into sub-objects.
So the general question is: how do you provide access to global application settings in your projects, without the need for global variables, while still being able to unit test your code? This must be a problem that's been solved 100's of times...
(Note: I'm not too much of an experienced programmer, as you'll have noticed; but I love to learn! And of course, I've already done research into this topic, but I'm really looking for some first-hand experiences)
You could use Martin Fowlers ServiceLocator pattern. In php it could look like this:
class ServiceLocator {
private static $soleInstance;
private $globalSettings;
public static function load($locator) {
self::$soleInstance = $locator;
}
public static function globalSettings() {
if (!isset(self::$soleInstance->globalSettings)) {
self::$soleInstance->setGlobalSettings(new GlobalSettings());
}
return self::$soleInstance->globalSettings;
}
}
Your production code then initializes the service locator like this:
ServiceLocator::load(new ServiceLocator());
In your test-code, you insert your mock-settings like this:
ServiceLocator s = new ServiceLocator();
s->setGlobalSettings(new MockGlobalSettings());
ServiceLocator::load(s);
It's a repository for singletons that can be exchanged for testing purposes.
I like to model my configuration access off of the Service Locator pattern. This gives me a single point to get any configuration value that I need and by putting it outside the application in a separate library, it allows reuse and testability. Here is some sample code, I am not sure what language you are using, but I wrote it in C#.
First I create a generic class that will models my ConfigurationItem.
public class ConfigurationItem<T>
{
private T item;
public ConfigurationItem(T item)
{
this.item = item;
}
public T GetValue()
{
return item;
}
}
Then I create a class that exposes public static readonly variables for the configuration item. Here I am just reading the ConnectionStringSettings from a config file, which is just xml. Of course for more items, you can read the values from any source.
public class ConfigurationItems
{
public static ConfigurationItem<ConnectionStringSettings> ConnectionSettings = new ConfigurationItem<ConnectionStringSettings>(RetrieveConnectionString());
private static ConnectionStringSettings RetrieveConnectionString()
{
// In .Net, we store our connection string in the application/web config file.
// We can access those values through the ConfigurationManager class.
return ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings["ConnectionKey"]];
}
}
Then when I need a ConfigurationItem for use, I call it like this:
ConfigurationItems.ConnectionSettings.GetValue();
And it will return me a type safe value, which I can then cache or do whatever I want with.
Here's a sample test:
[TestFixture]
public class ConfigurationItemsTest
{
[Test]
public void ShouldBeAbleToAccessConnectionStringSettings()
{
ConnectionStringSettings item = ConfigurationItems.ConnectionSettings.GetValue();
Assert.IsNotNull(item);
}
}
Hope this helps.
Usually this is handled by an ini file or XML configuration file. Then you just have a class that reads the setting when neeed.
.NET has this built in with the ConfigurationManager classes, but it's quite easy to implement, just read text files, or load XML into DOM or parse them by hand in code.
Having config files in the database is ok, but it does tie you to the database, and creates an extra dependancy for your app that ini/xml files solve.
I did this:
public class MySettings
{
public static double Setting1
{ get { return SettingsCache.Instance.GetDouble("Setting1"); } }
public static string Setting2
{ get { return SettingsCache.Instance.GetString("Setting2"); } }
}
I put this in a separate infrastructure module to remove any issues with circular dependencies.
Doing this I am not tied to any specific configuration method, and have no strings running havoc in my applications code.