Refactoring a Partial in October CMS - plugins

Good day,
I have several partials that have code. In the code tab, I noticed that the code tab had similar looking code. Here are examples
Partial 1
function onStart()
{
$x = MyModel1::where('myColumn', 'myValue')->first();
// lots of stuff using $x functions
$this['viewData'] = $x->getViewData();
}
Partial 2
function onStart()
{
$x = MyModel2::where('myColumn', 'myValue')->first();
// lots of stuff using $x functions
$this['viewData'] = $x->getViewData();
}
MyModel1 and MyModel2 both implement the same interface, so they have the same functions.
My question is, where do I put the code that is similar? I can put it in a plugin but that doesn't feel correct. I can create a base class and have the partials call the parent method but won't that mean modifying the code in the vendor folder?

if you really need to manage your code you can create component and add that code there as they easily attached to other pages (down point is that you need to create a plugin)
you can write your code inside onRun method.
https://octobercms.com/docs/plugin/components#page-cycle
and instead directly assigning variables to this you need to assign them like
$this->page['var'] = 'value';
and now it will work same as you are doing.

Related

Making a DFH functions Header file

Edit: This question is not off-topic as it describes an issue in data file handling with Turbo C++.
First of all, Turbo C++ is because of my school. Don't comment telling me to stop using it, I'm forced.
Introduction: I'm trying to build a DFH library, so I made all these functions to write, read, insert, delete, modify, etc.
I used stings to make the functions work for any filename passed to them.
What I understand (self-learned) from the whole making a class and then passing it's object in the read_stream.read((char*)& Object_1, sizeof(Object_1)); form to read the file, that you wrote using the same object is that: the class works as sort of a template to print data onto the file.
Question: I want to use them with different objects of different classes, so the class whose object these DFH functions use for performing the desired task should be sort of like a template.
I was thinking on doing something with templates or abstract class and inheritance but I'm a beginner so I need someone to point me in the right direction!
To clear up: I want to use the same functions by just including this source file into other programs containing different classes.
Example Code
class Data {
int user_id;
public:
void enter() { //Input Function
cout<<"\nID: ";
cin>>user_id;
};
void write(char* file_1) { //File Write Function
clrscr();
Data Object_1;
char ch;
int records_read =0;
ofstream fout;
fout.open(file_1, ios::binary|ios::noreplace);
do {
records_read++;
Object_1.enter(records_read);
fout.write((char*)& Object_1, sizeof(Object_1));
cout<<"\nDo you want to continue? Y/N - ";
cin>>ch;
} while((ch=='y')||(ch=='Y'));
cout<<"\nWrite Successful!";
fout.close();
}
How do I make the function write() work with any other class, without having to explicitly change the statement Data Object_1; ?

How to define own functions in zend framework

Actually I wanted to know that is there any way to define and call a function in Zend framework which does not need to put with $this like pr() function in cake php. I want to define a such a function which can be called directly in all controllers and views in zend framework. Can it be done by putting all functions in helper and use them without writing $this in front of them.
For example I wanted to make a function arrprint() to print the array in helper and use it globally with only by writing simply arrprint();
Please help me
You could just create a file anywhere and put the function in there. The just include it like you would any other files.
Or create a library called Utils and put your custom functions there as static and call them using:
Utils::myFunction();
Contrary to cake zf does not enforce much anything. You can leverage the framework to do whatever you want.
BTW $this is just a pointer to the current class and when you use $this->myFunction(); it's because that function is a member of the current class (or its parent).

Is it ok to use action helpers not only for controllers?

I'm looking for best way of using session within zf application.
At first I did something like this - in init method of controller superclass I initialized session:
class Vovkin_Controller_Action extends Zend_Controller_Action
{
protected $_session;
public function init()
{
// here I define namespace
// ...
$this->_session = new Zend_Session_Namespace($nameSpace);
parent::init();
}
...
}
after that session in controller was used in this way:
public function someAction()
{
$this->_session->user = $user;
}
but I found this approach not very handy for other parts of system, like plugins, services, etc, because there I had to init session in other way, but I want keep it in one place if it's possible. So I decided to change it to this approach https://stackoverflow.com/a/2506447.
Now I have a few action helpers to provide access for sessions with different namespaces, it works like this:
public function someAction()
{
$this->_helper->session()->user = $user;
}
and so far it looks useful, because I can get access to session namespaces in other parts of system, for example in services, in this way:
class Vovkin_Model_Service_UserLoginService
{
public function login()
{
$session = Zend_Controller_Action_HelperBroker::getStaticHelper('session')->direct();
...
}
....
}
but how much it's correct to use it in this way, from point of architecture and used resources?
Thanks.
The answer you have refereed to is from Rob Allen, one of the main contributors of Zend Framework, so it's right to some extent. You can go with the action helpers on controllers without any problems.
But outside it, it's completely wrong. Services doesn't has nothing with action helpers and the front controller. You can't put a dependency on it (services to action helpers).
So, as the application bootstrap works as a container for initializing the application, it's reasonable to get the necessary values from there. The first thing I would suggest you is to use Zend_Registry. But as far as I cal tell you, it would be the same initializing the session object again, since it will not be wiped, it's just an object referencing the native $_SESSION superglobals. So, simply call
new Zend_Session_Namespace($nameSpace).
But again, this is wrong. You should not let your services know how sessions are handled (thus creating the objects inside it):
$session = Zend_Controller_Action_HelperBroker::getStaticHelper('session')->direct()
or even
$session = Zend_Registry('userSession')
or
$session = new Zend_Session_Namespace('userSession')
With that you are also not using the bootstrap container at all. Instead you should provide a common interface to deal with sessions (it could be $_SESSION or even a database) and inject it into the service as a parameter (e.g. __construct($session)). But that's a whole new subject (Dependency Injection).
So, you have two options considering the current state of the ZendFramework 1.11 (that's already old and full of bad practices):
1) You'll use services through controllers:
So you will get the session through the action helper and then pass it as a parameter to your service.
new Vovkin_Model_Service_UserLoginService($session)
2) You will use services independently of controllers and will get the dependencies through the bootstrap container:
Well, the worst thing is that to get the bootstrap you need to have a frontController dependency.
$bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
So, avoid it, and go with the first option, injecting the dependency instead. Although, if you really want it in that way, access it directly:
$bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
$bootstrap->get('userSession')
Sadly, in the end, it's everything wrong. But it's the best you can do with ZF 1. You should look forward to ZF 2 and Symfony 2 to better understand these concepts.
Here it's a good explanation: http://symfony.com/doc/current/book/service_container.html
(I know that you're using ZF, but it doesn't matter, the concept is the key)

Magento: Accessing models/blocks from a phtml

Hi I have a situation where I need to look up the number of recently viewed products on catalog/product/view.phtml. In the recently viewed 'product_viewed.phtml' file it calls
$_products = $this->getRecentlyViewedProducts()
to get the recently viewed. How would I access this method from within the catalog/product/view.phtml file?
I don't know where this method is. I've tried searching for it but it doesn't seem to exist. When I write click it in Netbeans and click go to declaration it takes me to
class Mage_Reports_Block_Product_Viewed extends Mage_Reports_Block_Product_Abstract
Actually on the class itself. This class only has _toHtml(), getCount(), and getPageSize() methods.
I just need to know whether there are any recently viewed products.
Any help most appreciated!
Billy
If you look into 'Mage_Reports_Block_Product_Viewed', you will notice:
$this->setRecentlyViewedProducts($this->getItemsCollection());
That 'getItemsCollection' method is defined in the abstract class... And you will notice this abstract class will create a model based on $_indexName defined in the (subclassed) block.
If you just want the collection, you can probably get away with:
$_products = Mage::getModel('reports/product_index_viewed')->getCollection();
And then adding whatever you want to the collection:
$_products
->addAttributeToSelect('*')
->setAddedAtOrder();
// optionally add other methods similar to Mage_Reports_Block_Product_Abstract::getItemsCollection
Another approach that might be more suited would be to create the original block:
$productViewedBlock = $this->getLayout()->createBlock('reports/product_viewed');
On which you can simply call whatever you want:
$_collection = $productViewedBlock->getItemsCollection();
$_count = $productViewedBlock->getCount();
The getRecentlyViewedProducts function is a magical getter that gets the data that was set with setRecentlyViewedProducts in app/code/core/Mage/Reports/Block/Product/Viewed.php (which builds it using app/code/core/Mage/Reports/Block/Product/Abstract.php's function _getRecentProductsCollection).
This is complicated stuff that you don't want to reproduce; its better, IMO to make your own Block that extends Mage_Catalog_Block_Product_Abstract that will give you access to the same functionality, and drop your new block into the page you're working on.

How Do You Create Multiple Instances of a Library Class in CodeIgniter?

I'd like to create several instances of a class in CodeIgniter. I have created my class as a library, but cannot figure out the syntax to use to create more than one instance.
From the CodeIgniter users guide:
CI Users Guide: Loader Class
Assigning a Library to a different object name
If the third (optional) parameter is
blank, the library will usually be
assigned to an object with the same
name as the library. For example, if
the library is named Session, it will
be assigned to a variable named
$this->session.
If you prefer to set your own class
names you can pass its value to the
third parameter:
$this->load->library('session', '',
'my_session');
Session class is now accessed.
using:
$this->my_session
I think that's what you're looking for.
I know this thread is long passed, but it was one of the questions I came across while looking for my answer. So here's my solution...
It's PHP. Create your class as a library, load it using the standard CI Loader Class, but use it like you would in a regular PHP script.
Build your class:
class My_class {
var $number;
public function __construct($given_number){
$number = $given_number;
}
public function set_new_num($given_number){
$number = $given_number;
}
}
Load it:
// This will load the code so PHP can create an instance of the class
$this->load->library('My_class');
Then instantiate and use the object where needed:
$num = new My_class(24);
echo $num->number;
// OUTPUT: 24
$num->set_new_num(12);
echo $num->number;
// OUTPUT: 12
The only time I use $this->my_class is to make calls to static functions that I code.
Sorry for reviving this topic but I think I might have something reasonable to add.
You can do this to add multiple instances of a class. I don't know if it violates Codeigniter standard usage anyhow but seems more Codeigniterish than loading a library (which creates $this->library_name which isn't used) and then making 2 MORE instances with the "new" keyword.
$this->load->library( 'my_library', '', 'instance1' );
$this->load->library( 'my_library', '', 'instance2' );
$this->instance1->my_class_variable = 1;
$this->instance2->my_class_variable = 2;
echo $this->instance1->my_class_variable; // outputs 1
echo $this->instance2->my_class_variable; // outputs 2
I use this in my code to generate different menus. I have a "menu" class and different instances for each menu, with different menu items in each.